can you use c code to read a .txt file size?

112 views Asked by At

this is all very new to me and i'm trying to see if i can return the size of a text file included in a c program.

#include <stdio.h>
#include "Test1.txt"

int main()
{

}

I'm reading a lot about an fseek function but not sure how to implement it

1

There are 1 answers

2
unwind On

You're not making sense, I'm afraid.

It doesn't make sense to "include a text file in a C program" like you did. A text file does not contain C code (typically), so it can't be included in C source code. The compiler doesn't know how to deal with that.

The way to check the size of a text file, any text file and not one "included" in the program, is to use a combination of I/O functions. You need to

  1. Open the file with fopen()
  2. Go to the end of the file with fseek()
  3. Check the position that you're at with ftell(); this will be the size of the file since you know you're at the end
  4. Close the file with fclose()

The file name can be hardcoded to e.g. "Test1.txt" if you want your program to always check the size of the same file, or it can be handled as a command-line argument using argc and argv (which you've omitted from your main()).