GONGJUNRUI123 2018-01-29 23:32 采纳率: 33.3%
浏览 2306
已结题

用stat函数无法获取文件大小

各位,我打算用stat里面的st-size 函数获取文件的大小,但是怎么调试得到的值就是0.

 int
main (void)
{
    char *fileName = "abcd.txt";

    SM_FileHandle fh;

    createPageFile(fileName);

    openPageFile (fileName, &fh);
    int a = fh.totalNumPages;
    printf("%d+%s", a, "main");

    return 0;
}
 RC createPageFile (char *fileName){
    FILE *pageFile;
    pageFile = fopen(fileName,"w");   //Creates an empty file for both reading and writing.
//    for(int i = 0; i < PAGE_SIZE; i++){      //Creates one page in the file. The size of page is 4096 bytes
//        fwrite("\0", 1, 1, pageFile);
//    }

     fwrite("abc", 3, 1, pageFile);


    struct stat fileStat;
    stat(fileName, &fileStat);
    int fileSize = fileStat.st_size;   //Get the size of file.

    printf("%d+%s\n", fileSize, "create file");

    return RC_OK;
}
 RC openPageFile (char *fileName, SM_FileHandle *fHandle){
    FILE *pageFile;
    pageFile = fopen(fileName,"r");  //Opens the file.

    if(pageFile == NULL){            //If cannot found the file, return "RC_FILE_NOT_FOUND".
        return RC_FILE_NOT_FOUND;
    }else{
        struct stat fileStat;
        stat(fileName, &fileStat);
        int fileSize = fileStat.st_size;   //Get the size of file.

        fHandle->fileName = fileName;
        fHandle->totalNumPages = fileSize/PAGE_SIZE;
        fHandle->curPagePos = 0;
        fHandle->mgmtInfo = pageFile;

        printf("%d+%s\n", fileSize, "open file");

        return RC_OK;
    }
}
  • 写回答

4条回答 默认 最新

  • 熊爱溪 2018-02-11 01:46
    关注

    你需要在用fopen创建文件后,调用fclose,因为在向文件写数据时,实际是将数据输到缓冲区,待缓冲区充满后才正式输出给文件,如果当数据未充满缓冲区而程序结束运行,就会将缓冲区中的数据丢失。用fclose函数关闭文件,他先将缓冲区中的数据输出到磁盘文件然后才释放文件指针变量,从而避免了数据丢失。而stat是用来获取文件的实际状态的,没用fclose的话,实际数据没有保存到文件中,获取的st_size就是0了。

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办