0

I'm reading a file called data.txt with looks like the following:

b    5
b    2
b    9

Each line has 3 characters: the space between being a tab.

I have the following code to read one line at a time.

int main(int argc, char * argv[]){
    FILE * filePointer;
    filePointer = fopen("data.txt", "r");
    char singleLine[3*sizeof(char)];

    while(!feof(filePointer)){
        fgets(singleLine, 3*sizeof(char), filePointer);
        //printCharArray(singleLine); 
        puts(singleLine);
    }

    fclose(filePointer);
    return 0;
}

singleLine is basically the buffer that the text of each line is put into. I originally made it like char singleLine[20], an arbitrary big enough number, but I want it to be exact so I did char singleLine(3*sizeof(char)). My logic was each line has 3 characters, so this should work.

Sadly it did not, when running it, it printed out like the following:

b 

5

b 

2

b 

9

When I do the careless way, char singleLine[20], it works correctly as shown below. But I want to do it the correct way. What is wrong?

b    5
b    2
b    9
James Mitchell
  • 2,387
  • 4
  • 29
  • 59
  • Not an answer to your question, but: `sizeof(char)` is always `1`, so there's rarely any reason to write it explicitly. – ruakh Sep 24 '17 at 04:18
  • The *correct way* is not to be so stingy with your buffer size. If you think your max size is `3`, then a `32` char buffer should suffice. And see [**Why is while ( !feof (file) ) always wrong?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – David C. Rankin Sep 24 '17 at 04:23
  • 4
    `fgets()` wants to read a _line_ of text like `b`, `tab`, `5`, `line feed` - that is 4 characters. After reading a _line_, `fgets()` appends a _null character_. So `singleLine[]` should be at least `singleLine[5]`. – chux - Reinstate Monica Sep 24 '17 at 04:24

1 Answers1

2
  1. Your array has room only for two characters and the null terminator.
  2. Your lines have four characters (including a newline).
Davis Herring
  • 36,443
  • 4
  • 48
  • 76