How to get a file size in C

3 Answers

0 votes
#include <stdio.h>

int main() {
    char file[64] = "d:\\data.txt";
    FILE *fp = fopen(file, "r");

    fseek(fp, 0L, SEEK_END);
    long fsz = ftell(fp);

    fclose(fp);

    printf("%ld bytes\n", fsz);

    return 0;
}




/*
run

40 bytes

*/


 



answered Jul 8, 2020 by avibootz
edited May 2, 2021 by avibootz
0 votes
#include <stdio.h>
#include <sys/stat.h>

int main() {
	const char* filename = "d:\\data.txt";

	struct stat sb;
	stat(filename, &sb);

	printf("%ld bytes\n", sb.st_size);

	return 0;
}





/*
run
 
40 bytes
 
*/

 



answered May 2, 2021 by avibootz
edited Dec 15, 2022 by avibootz
0 votes
#include <stdio.h>
  
long int findFileSize(char file_name[]) {
    FILE* fp = fopen(file_name, "r");
  
    if (fp == NULL) {
        printf("File Not Found\n");
        return -1;
    }
  
    fseek(fp, 0L, SEEK_END);
  
    long int size= ftell(fp);
  
    fclose(fp);
  
    return size;
}
  
int main()
{
    char file_name[] = "d:\\data.txt";
     
    long int fsize = findFileSize(file_name);
     
    if (fsize != -1)
        printf("Size = %ld bytes\n", fsize);
         
    return 0;
}
     



/*
run:
  
Size = 28 bytes
  
*/

 



answered Dec 15, 2022 by avibootz

Related questions

1 answer 264 views
1 answer 205 views
1 answer 231 views
231 views asked Dec 22, 2015 by avibootz
1 answer 219 views
219 views asked Oct 18, 2014 by avibootz
...