Reputation: 227
for some reason I get exeception after the line:
currentString[i] = *currentChar;
This code is ment to gather all of the the characters from a file, till it encounters the character ';', and put them in a string. Does anyone knows what's the deal? thanks! This is all of the code:
char currentString[100] = { 0 };
char *currentChar;
//opening the input file
FILE *input = fopen("input.txt", "r");
//if the file doesn't exist, the pointer will contain NULL
if (input == NULL)
{
exit(1);
}
//assigning the start of the input file adress to currentChar
currentChar = input;
//while the current character isn't the last character of the input file
while (currentChar < input + strlen(input) + 1)
{
while (currentChar != ';')
{
currentString[i] = *currentChar;
printf("%c", *currentChar);
currentChar = currentChar + 1*sizeof(char);
i++;
}
}
Upvotes: 0
Views: 100
Reputation: 223872
You're not reading from the file at all. This:
currentChar = input;
Assigns the address of the FILE
object pointed to by input
to currentChar
. This is also a type mismatch because you're assigning a FILE *
to a char *
. You also can't use strlen
on input
because it is not a char *
. You should have gotten plenty of compiler warnings about these.
To read characters from a file, use the fgetc
function:
int currentChar = fgetc(input);
//while the current character isn't the last character of the input file or a ';'
while (currentChar != EOF && currentChar != ';')
currentString[i] = currentChar;
printf("%c", currentChar);
currentChar = fgetc(input);
i++;
}
Upvotes: 1
Reputation: 42129
input
is a pointer to an opaque FILE
type, not a pointer to the contents the file as you seem to assume. This means you cannot access the contents of the file through the pointer directly. Instead, you need to pass input
to functions that read input from the file, such as fgets
, getc
and fscanf
.
Upvotes: 3