Question

I thought I understood fstat, I was wrong.

I need to know the size of the file then read from the file.

fileN Has the path of the file and the name of the file. It looks like this. 0.txt

struct stat fileStat;

FILE *fp;
int fd = 0; 


int i;
for(i = 0; i < 100; i++)
{
   fp = fopen(fileN, "r");

   fd = open(fileN, "r"); // I think this is eating my files and making them 0 size.
   fstat(fd, $fileStat);

   printf("%d", fileStat.st_size);

   fclose(fp);
}

Why do I need to use fd = open(fileN, "r"); To use fstat? It feels like I am opening the file twice.

If fileStat is a struct why do I use fileStat.st_size instead of fileStat->st_size like I do when I create my own structs? Example: myString->characters;

And why is the code above printing 0s when printf is executed? And yes the files have a size bigger than 0 and I have the correct file name and path.

All code above is my interpretation of code that was Googled and mixed with my trial and error implementation. That's why I have so many questions.

EDIT: SOLUTION: open() was being called wrong and affecting the files.

Was it helpful?

Solution

  • Why do I need to use fd = open(fileN, "r"); To use fstat? It feels like I am opening the file twice.

Because fstat() requires a file descriptor. You could use stat() instead, which takes a filename. Or you could use fd = fileno(fp) to get the file descriptor from the stdio FILE.

BTW, you need to call close(fd) in the loop.

  • If fileStat is a struct why do I use fileStat.st_size instead of fileStat->st_size like I do when I create my own structs? Example: myString->characters;

You use -> when the variable on the left is a pointer to a struct, you use . when it's the struct itself. This is basic C syntax, nothing specific to fstat.

  • And why is the code above printing 0s when printf is executed? And yes the files have a size bigger than 0 and I have the correct file name and path.

You're not calling open() correctly. The second argument is supposed to be an int containing flags. Since you give a string instead, the pointer to the string is being coerced to an int, and the bits in this are probably not valid open flags. You need to check the return value of open to see if it succeeded -- it will return -1 if there's an error. Similarly with fstat -- it's probably returning an error because fd is not valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top