How to get the file length in c on linux?

Member

by lia , in category: General Help , 7 months ago

How to get the file length in c on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by samara , 7 months 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.

Member

by ethelyn , 2 months ago

@lia 

This code snippet provides a simple way to get the length of a file using the stat() function in C on a Linux system. In the provided code:

  1. The necessary header files stdio.h and sys/stat.h are included.
  2. A variable st of type struct stat is declared to hold the file information.
  3. A constant character pointer filename is initialized with the name of the file whose length is to be determined.
  4. The stat() function is called to retrieve the file information, and if it returns successfully (i.e., returns 0), the size of the file is printed using the st_size member of the st structure.
  5. If the stat() function fails, an error message is printed.


Remember to replace "example.txt" with the name of the file for which you want to get the length. This code snippet will help you in accomplishing this task.