Saturday, 11 May 2019

Learning how to Read and output Lines in a file in C

The first issue I see is this idiom:


while((c = fgetc(myFile) != EOF))

has the parens wrong, it should be:


while ((c = fgetc(myFile)) != EOF)

Also, this count:


start = line - num; //Start location

has an off-by-one error:


int start = line - num - 1; // Start location

Beyond that, your array seems too small for general text line processing:


char c, array[100];

Putting it all together with a few style tweaks, we get:


// Tail function that prints the lines
// according to the user specified number of lines
void tail(FILE *myFile, int num)
{
int line = 0;
char c;
while ((c = fgetc(myFile)) != EOF)
{
if (c == '\n')
{
line++;
}
}
int start = line - num - 1; // Start location
(void) fseek(myFile, 0, SEEK_SET); // Go to the start of the file
int counter = 0;
char array[1024];
while (fgets(array, sizeof(array), myFile) != NULL)
{
if (counter > start)
{
fputs(array, stdout); // Print the string
}
counter++;
}
fclose(myFile); // Close the file
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...