自制fstat获取文件大小,总是返回0长度

发布于 2024-08-26 09:13:52 字数 266 浏览 5 评论 0原文

我正在尝试使用我自己的函数从文件中获取文件大小。我将使用它为数据结构分配内存以保存文件信息。

文件大小函数如下所示:

long fileSize(FILE *fp){
    long start;
    fflush(fp);
    rewind(fp);
    start = ftell(fp);
    return (fseek(fp, 0L, SEEK_END) - start);
}

你知道我在这里做错了什么吗?

I am trying to use my own function to get the file size from a file. I'll use this to allocate memory for a data structure to hold the information on the file.

The file size function looks like this:

long fileSize(FILE *fp){
    long start;
    fflush(fp);
    rewind(fp);
    start = ftell(fp);
    return (fseek(fp, 0L, SEEK_END) - start);
}

Any ideas what I'm doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

真心难拥有 2024-09-02 09:13:52

这样做

fseek(fp, 0L, SEEK_END);
return (ftell(fp) - start);

而不是

return (fseek(fp, 0L, SEEK_END) - start);

因为 fseek 在成功时返回零,而不是像你这样的偏移量期待在这里。

Do

fseek(fp, 0L, SEEK_END);
return (ftell(fp) - start);

instead of

return (fseek(fp, 0L, SEEK_END) - start);

because fseek return zero on success not the offset as you are expecting here.

水波映月 2024-09-02 09:13:52

一些评论:

  • 不要调用 fflush() - 您的流可能是读取流,fflush() 会导致未定义的行为

  • 您没有任何错误检查!

  • fseek() 成功返回 0 - 您需要调用 ftell() 来获取长度

将代码更改为:

long fileSize(FILE *fp)
{    
    fseek(fp, 0L, SEEK_END);
    return ftell(fp);
}

A few comments:

  • don't call fflush() - your stream might be a read stream, for which fflush() results in undefined behaviour

  • you don't have any error checking !

  • fseek() returns 0 for success - you need to call ftell() to get the length

Change the code to this:

long fileSize(FILE *fp)
{    
    fseek(fp, 0L, SEEK_END);
    return ftell(fp);
}
漫漫岁月 2024-09-02 09:13:52

您需要在fseek之后调用ftell。尝试:

long fileSize(FILE *fp){
  long start;
  fflush(fp);
  rewind(fp);
  start = ftell(fp);
  fseek(fp, 0L, SEEK_END);
  return ftell(fp);
}

没有必要做任何改变,所以你的第一个ftell是无用的,你可以摆脱它。我会使用:

long filezise(FILE *fp)
{
  fseek(fp,OL,SEEK_END);
  // fseek(f, 0, SEEK_SET); - only if you want to seek back to the beginning
  return ftell(fp);
}

另外,请确保以二进制模式打开文件。

You need to call ftell after fseek. Try:

long fileSize(FILE *fp){
  long start;
  fflush(fp);
  rewind(fp);
  start = ftell(fp);
  fseek(fp, 0L, SEEK_END);
  return ftell(fp);
}

There's no need to do a difference, so your first ftell is useless and you can get rid of it. I would use:

long filezise(FILE *fp)
{
  fseek(fp,OL,SEEK_END);
  // fseek(f, 0, SEEK_SET); - only if you want to seek back to the beginning
  return ftell(fp);
}

Also, make sure you open your file in binary mode.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文