There is nothing wrong with reading from a file up-to the first space
character with fgetc
, however, there are several problems with:
if (fgetc(grades) != ' ')
{
currChar = fgetc(grades);
className[i] = currChar;
i++;
}
When you call fgetc(grades) != ' '
, a character is read from grades
and then the file-position-indicator is advanced to the next character. So when you call fgetc
inside the if
statement, you read a character and then the file-position-indicator is advanced in preparation for reading the next character. When you then call fgetc
again in the body of the if statement (currChar = fgetc(grades);
), you read the second character in the file. It seems rather obvious from your question, that your intent was not to skip-a-character and then begin reading with the next.
When you read input with any character-oriented-input function (e.g. getchar
, fgetc
, etc.) there are three primary things you are responsible for: (1) insuring you do not attempt to write more characters to your storage variable than it will hold; (2) check for any sentinel or terminating character you wish to stop the read with; and (3) checking that you have not reached the end of the input stream.
Putting those pieces together you could do something like:
#include <stdio.h>
#define MAXCN 10
int main (void)
{
FILE* grades = NULL; /* initialize variables */
char className[MAXCN] = {0};
int currChar = 0; /* currChar is an int */
int i = 0;
/* open and validate file */
if ((grades = fopen("grades.txt", "r")) == NULL) {
fprintf (stderr, "error: file open failed 'grades.txt'.\n");
return 1;
}
/* read from grades until 1st space */
while (i + 1 < MAXCN && ((currChar = fgetc (grades)) != ' ' &&
currChar != EOF)) {
className[i++] = currChar;
}
className[i] = 0; /* null-terminate */
printf("\n className: %s\n\n", className);
return 0;
}
Note: when you stop reading on any character, the next read will resume on the next character in the input stream. So you will need to empty any characters that remain (in the line, etc...) if you want to begin your read at any than other than the next character. Also note, when you open a file with fopen
, you should validate that the open actually worked before proceeding to read from the file.
Input
$ cat grades.txt
Homeroom grades are include below
Output
$ ./bin/fgetc_grades
className: Homeroom
Hopefully this will help you get started, let me know if you have any additional questions.