C语言 如何查找到文件末尾以确定文件大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7757184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:53:39  来源:igfitidea点击:

how to seek to the end of file to determine the file size?

cfilesizeseek

提问by Abhilash Muthuraj

I'm trying to get file size in c programming using seek. I can't use fseek, stat.size nor ftell, there's a custom operating system UNIX in which I need to run.

我正在尝试使用seek在c编程中获取文件大小。我不能使用fseek, stat.size 也不能使用,ftell我需要在其中运行自定义操作系统 UNIX。

How can I find out filesize just by using seek? Is it possible?

如何仅通过使用查找来找出文件大小?是否可以?

  FILE *fd = open(argv[1], "r");

  if(fd == NULL)
  {
    printf("Not able to open the file : %s\n", argv[1]);
    return;
  }

  // Set the pointer to the end
  seek(fd, 0, SEEK_END);

回答by Nordic Mainframe

seek? You mean lseekprobably. Have a look at the manual page. What does lseekreturn?

seek? 你的意思是lseek大概。看看手册页。什么lseek回报?

回答by alk

If you are just wondering whether the construct using offset = 0with whence = SEEK_ENDwould position the file offset to the end of the file, then "yes" you are right, at least for the "standard f/lseek()"s I came across.

如果您只是想知道使用offset = 0with的构造是否whence = SEEK_END会将文件偏移量定位到文件的末尾,那么“是”您是对的,至少对于f/lseek()我遇到的“标准”。

lseek()should directly return the file offset. For fseek()a following ftell()will get you the file offset.

lseek()应该直接返回文件偏移量。对于fseek()一个下面ftell()将让你的文件偏移。

回答by Brian McFarland

Normally, open()returns an int, not a FILE *. You have to check for a return value >= 0. fopen()from <stdio.h>returns a FILE *. Also, for the record, fopen()and fseek()are part of the C standard library. A UNIX open() is part of POSIX. So in general, fopen()/ fseek()is more portable.

通常,open()返回一个 int,而不是一个FILE *. 您必须检查返回值 >= 0. fopen()from<stdio.h>返回 a FILE *。另外,为了记录,fopen()并且fseek()是 C 标准库的一部分。UNIX open() 是 POSIX 的一部分。所以总的来说,fopen()/fseek()更便携。

If you are really on a custom "Unix-like" environment, to where that is no longer true (i.e. you have an custom API instead of unistd.h) then you're not going to a good answer here without providing more info. Can you tell us what OS you are really running?

如果您真的在自定义的“类 Unix”环境中,而这不再适用(即您有一个自定义 API 而不是 unistd.h),那么如果不提供更多信息,您将不会在这里得到一个好的答案。你能告诉我们你真正运行的是什么操作系统吗?

Or like Luther suggested, check the return value of lseek()if you are using a normal <unistd.h>.

或者像 Luther 建议的那样,lseek()如果您使用的是普通<unistd.h>.