各位,我用fopen创建一个bin文件并写入数据,但是用 fileStat.st_size 发现 filesize结果总是0,请哪位大神可以解答
int main(void){
FILE *pageFile;
pageFile = fopen("abc.bin","w+");
fwrite("\0", 1, 1, pageFile);
struct stat fileStat;
stat("abc.bin", &fileStat);
int fileSize = fileStat.st_size;
}
写完调用一下fflush()试试
路径不对吧 换一个 路径试一下
你创建文件了吗? 这个路径有问题。
int main(void)
{
FILE *pageFile;
pageFile = fopen("abc.bin","w+");
fwrite("\0", 1, 1, pageFile);
struct stat fileStat; //这句话啥意思?
stat(fileName, &fileStat); //filename没有定义
int fileSize = fileStat.st_size; //不能在这里定义变量
}
你把你要表达的意思说清楚点,或许我能帮你解答
你需要在用fopen创建文件后,调用fclose,因为在向文件写数据时,实际是将数据输到缓冲区,待缓冲区充满后才正式输出给文件,如果当数据未充满缓冲区而程序结束运行,就会将缓冲区中的数据丢失。用fclose函数关闭文件,他先将缓冲区中的数据输出到磁盘文件然后才释放文件指针变量,从而避免了数据丢失。而stat是用来获取文件的实际状态的,没用fclose的话,实际数据没有保存到文件中,获取的st_size就是0了。
#include
#include
#include
static unsigned long getFileSize(const char *filePath)
{//EFile类获取文件大小
unsigned long filesize = -1;
struct stat statbuff;
if(stat(filePath, &statbuff) < 0)
return filesize;
else
filesize = statbuff.st_size;
printf("func %s, LINE %d----------filesize = %lu, filePath = %s,\n", func, LINE, filesize, filePath);
return filesize;
}
测试可以用,stat前保证该文件没有被打开