Hi all. I am learning how to use the debugger.
Here is a program that I wrote in the early days of learning C for displaying the contents of a text file to the screen.
I had always thought that it would grab 100 characters of a line(at a time) and then output to the screen, looping repeatedly, until fgets() == NULL. To my surprise, it seems to be storing several lines somewhere, and then only outputting them when fgets() == NULL. So it seems to output only once. Why is it doing this, and how can it be doing this when the buffer size is only 100?
Thanks.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILE_LENGTH 40
#define MAX_STRING_LENGTH 100
int main(void)
{
int count, file_length, string_length;
char filename[MAX_FILE_LENGTH], line[MAX_STRING_LENGTH];
FILE *openfile;
puts("Enter file to open");
fgets(filename, MAX_FILE_LENGTH, stdin);
string_length = strlen(filename);
filename[string_length-1] = '\0';
puts(filename);
if ((openfile = fopen(filename, "r")) != NULL)
puts("File opened successfully\n");
else
{
puts("Error opening file");
exit(1);
}
while(fgets(line, MAX_STRING_LENGTH, openfile ) != NULL)
{
printf("%s", line);
}
fclose(openfile);
return 0;
}