roneboy
roneboy

Reputation: 73

Check Text File Length In C

I have a text file, which has random amount of characters, numbers, spaces and new lines. I'm trying to figure out how to find the "length" of this file. For example: if the text file contains "This is an example." the lenght should be 19. I tried using both sizeof(text_file) and strlen(text_file), but they don't give me the desired output.

What I also tried was this:

 void test(FILE *f)
 {
     int i;
     i=0;
     char ch;

     while( ( ch = fgetc(f) ) != EOF ) {
         printf("%c",ch);    /*This is just here to check what the file contains*/
  
         if(ch!='\0') {
             i=i+1;
         }
     }

     printf("------------------\n");
     printf("The length of the file is\n");
     printf("%d",i);   /*For some reason my length is always +1 what it actually should be*\
}

Is there an easier way to do this and why does the code above always give +1? I guess there is something wrong with the if statement, but I don't know what.

Any help is really appreciated thanks in advance.

Upvotes: 4

Views: 17748

Answers (2)

Martin R
Martin R

Reputation: 539745

As others have already explained, there are better ways to determine a file size.

The reason that your code does not give the expected result is probably that your file contains a trailing newline character \n which is counted as well:

This is an example.\n

are 20 characters, not 19.

And note that you should declare int ch, not char ch for the EOF-check to work properly, compare fgetc, checking EOF.

Upvotes: 3

Devolus
Devolus

Reputation: 22084

As for the size you can do this:

 size_t pos = ftell(f);    // Current position
 fseek(f, 0, SEEK_END);    // Go to end
 size_t length = ftell(f); // read the position which is the size
 fseek(f, pos, SEEK_SET);  // restore original position

If you don't care about the position, you can of course omit resetting the current filepointer.

Upvotes: 3

Related Questions