-1

I am reading in a file, and I am trying to take the first character from that file, and assign to to a variable: currentChar

I am getting the following error message:

Incompatible types when assigning to type char from type FILE {aka struct _IO_FILE}

char inputFile[50] = "hello.txt"; 
FILE * inFile = fopen(inputFile, "r");
char currentChar;
currentChar = inFile[0];
fclose(inFile);
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
JoeW373
  • 59
  • 1
  • 11

2 Answers2

2

FILE is a structure holding metadata (filled in by fopen()), which is used as parameter by other functions that affect reading from the file. You never access what is in a FILE structure directly.

One of the file access functions is fgetc(), which takes a FILE * as parameter and returns an int -- either EOF (end-of-file) or the next character from the file so identified.

char inputFile[] = "hello.txt"; 
FILE * inFile = fopen(inputFile, "r");
// inFile == NULL means fopen() failed
if ( inFile != NULL )
{
    int currentChar;
    currentChar = fgetc( inFile );
    // check currentChar for EOF, then do something with it
    fclose(inFile);
}
else
{
    perror( "fopen() failed" );
}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • Good cleanup! you might also hint that `char inputFile[50] = "hello.txt";` is inadequate: `char inputFile[] = "hello.txt";` or `const char *inputFile = "hello.txt";` are safer alternatives, and using `fopen("hello.txt", "r")` is even simpler. – chqrlie Jan 20 '18 at 14:31
0

DevSolar gave a useful answer with corrections for your mistakes, and following his advice will let you read the file contents correctly.

Yet reading a file one character at a time may be more subtle than it looks: fgetc() or plain getc() returns either EOF or a byte from the file, a value of type unsigned char, which is necessarily the same type as char, and which does not necessarily represents a character, especially if the file is encoded with a multi-byte encoding such as UTF-8. This byte value can be safely stored to a char variable, but how to interpret it is the programmer's responsibility, depending on the actual file type and encoding.

chqrlie
  • 131,814
  • 10
  • 121
  • 189