题
当我运行我的程序并且我选择查看产品列表时,它不会打印任何内容。过了一段时间,我发现 fl_size
始终为0。这是为什么?
void view_prdct_code_list() {
FILE *stock = fopen("stock.dat","r+");
assert(stock);
int fl_size=ftell(stock);
int prd_size= sizeof(product);
int quantity= fl_size/prd_size;
printf("fl_size=%d",fl_size);
fseek(stock,0,SEEK_SET);
prdct cprd= (product *)malloc (sizeof(product)*quantity);
assert(cprd);
int i;
fread(cprd,prd_size,quantity,stock);
for (i=0;i<quantity;i++){
printf("PRODUCT CODE: %d\n",cprd->code);
}
free(cprd);
fclose(stock);
}
解决方案
ftell
不返回文件的总大小;它返回当前 读或写位置 文件内。你打电话 ftell
打开文件后立即,使该位置是文件的最开始。您可以使用 fseek(stock, 0, SEEK_END)
在打电话之前寻求到最后 ftell
, ,或者你可以下拉一个图层并使用 fstat(fileno(stock))
直接从操作系统中检索文件大小。
进一步注意事项:
- 如果您从管道读取,这些选项都不起作用。(通常,您需要检查每个文件访问操作是否成功。)
fread
即使您要求它,也不能保证一次读取整个文件。- 正如'alk'所指出的那样,
ftell
返回along
, ,不是一个int
. - 你应该用模式打开这个显然是二进制文件
"r+b"
. - 没有文件头的二进制文件(特别是没有 魔术数字, ,至少四个字节,在偏移零)是一件坏事。
- 不要强制转换返回值
malloc
.(有必要在C++中做到这一点,但在C中它不仅是不必要的, 它可以隐藏bug.)
其他提示
检查手册页 ftell
, ,例如这一个: http://linux.die.net/man/3/ftell
以下是相关部分: "Ftell()函数获取stream所指向的流的文件位置指示符的当前值。"
当您打开文件时,光标位置将在开始处。所以从开始的距离将是零。因此 ftell
返回零。
要查找文件大小,请参阅此链接: 如何在C中获取文件大小?.这里有一个简短的片段:
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
一定要打电话 fseek(fp, 0L, SEEK_SET);
上面之后。
Because ftell
returns the size from the beginning to the current position of the file.
fseek(stock,0,SEEK_SET);
Means you set the position to the first bite of the file.
Also you gotta set fl_size=ftell(stock);
after the fseek
.
不隶属于 StackOverflow