Saturday, November 27, 2010

Reading c file line by line using fgetc()

Programmer Question

This is how I done it but I'm not sure this is the preferred idiom:



FILE *fp = fopen(argv[0], "r");
// handle fopen() returning NULL

while (!feof(fp)) {
char buffer[80]; // statically allocated, may replace this later with some more sophisticated approach
int num_chars = 0;

for (int ch = fgetc(fp); ch != EOF && ch != '\n'; ch = fgetc()) {
buffer[num_chars++] = ch;
}

// null-terminate the string
buffer[num_chars] = '\0';

printf("%s\n", buffer);
}


Is this okay, any suggestions to improve this?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails