-1
char * file = malloc(buffer);
assert(file != 0);
char str[20];

snprintf(file, buffer, "%s/%s", newestDirName, fileInDir->d_name);
FILE * input = fopen(file, "r"); // read
fseek(input, 0, SEEK_END);
fgets(str, 20, input);
printf("str = %s \n", str);

The file I am reading from has the last line:

ROOM TYPE: END_ROOM

Why isn't str storing "ROOM TYPE: END_ROOM"

I thought fseek(input, 0, SEEK_END) gets the last line with the cursor starting at the leftmost position of the last line. Is this wrong?

I thought fgets(str, 20, input) gets 20 characters from input and puts it into str which is a char * variable.

But I get gibberish for str's value when I print str:

str = ▒▒As=   
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 3
    Just what do you think will be read *next* from a file after you seek all the way to the *end*? – Andrew Henle May 15 '17 at 00:18
  • 3
    You seek to the end of the file; there is nothing after the end of the file for `fgets()` to read. It does not seek to the start of the last line before the end of the file. Note that `fgets(str, 20, input)` reads up to 19 characters and places a null byte after the last character. It may read fewer than 19 characters if the newline appears before the 19th character, and adds a null byte to the 20th position. You should always test the return value from input functions — the return value from `fgets()` would be NULL indicating EOF. And on EOF, the string is not set to any determinate value. – Jonathan Leffler May 15 '17 at 00:20

1 Answers1

0

If you need to use fgets, you can try this.However, nothing guarantees that the number of characters in a line does not exceed 20 characters,Especially if the number of characters is variable on each line.

char str[20]={0};
FILE * input = fopen("file.txt", "r"); // read
if(input)
{
    char *ptr;/*Warns you if you have reached the end of the file or some error*/
    do 
    {   
        ptr=fgets(str, 20, input);
    } while(ptr);
    if(str)
        printf("str = %s \n", str);
    fclose(input);
}