Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Text File Length In C

Tags:

c

file

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.

like image 925
roneboy Avatar asked Sep 15 '25 23:09

roneboy


1 Answers

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.

like image 171
Devolus Avatar answered Sep 19 '25 06:09

Devolus