How to get the file length in c on linux?

Member

by lia , in category: General Help , 25 days ago

How to get the file length in c on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 23 days ago

@lia 

In C language, you can use the stat function from the sys/stat.h header file to get the file length. Here's an example of how you can do it on Linux:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <sys/stat.h>

int main() {
    struct stat st;
    const char* filename = "example.txt";  // Replace with your file name

    if (stat(filename, &st) == 0) {
        printf("File size: %lld bytes
", (long long) st.st_size);
    } else {
        printf("Failed to get file size.
");
    }

    return 0;
}


Explanation:

  1. Include the necessary header files stdio.h and sys/stat.h.
  2. Declare a variable of type struct stat to hold the file information.
  3. Specify the file name whose length you want to determine. Change "example.txt" to your desired file name.
  4. Use the stat function to retrieve the file information and store it in the st structure.
  5. Check if the stat function was successful. If so, print the file size using the st_size field of the st structure.
  6. If the stat function fails, print an error message.