各位,我打算用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;
}
}
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;
}
}
你需要在用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前保证该文件没有被打开
可能是你之前写的时候打开了没关,光标定义在文件末尾了 你试试把文件光标定义在开头 ,或者关闭文件