读取文件直到内容结束(到达 EOF)

发布于 2025-01-17 01:15:34 字数 752 浏览 5 评论 0原文

(尽管事实上,一次读取1个字符对系统来说是昂贵的)为什么以下函数在文件内容结束后没有停止?目前,我正在使用命令行输入作为文件路径并使用cmd作为终端来运行该函数。

这是代码:

int flen(int file){
    int i;
    char c = 0;
    for(i = 0; c != EOF; i++){
        read(file, &c, 1);
    }
    return i;
}

int main(int argc, char *argv[]){
    long long len;
    int fd;
    if(argc != 2){
        fprintf(stderr, "Usage: %s <valid_path>\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    if((fd = open(argv[1], O_RDONLY, 0)) == -1){
        fprintf(stderr, "Fatal error wihile opening the file.\n");
        exit(EXIT_FAILURE);
    }

    len = flen(fd);
    printf("%d\n", len);

    exit(0);
}

我认为问题可能与 for 循环条件中的 EOF 有关。但如果这是真的,我怎么知道文件何时真正结束?

(Despite the fact, reading 1 char at time is system expensive) Why the following function is not stopping after the content of a file ended? Currently I am running the function using command line inputs for the path of the file and cmd as teminal.

Here is the code:

int flen(int file){
    int i;
    char c = 0;
    for(i = 0; c != EOF; i++){
        read(file, &c, 1);
    }
    return i;
}

int main(int argc, char *argv[]){
    long long len;
    int fd;
    if(argc != 2){
        fprintf(stderr, "Usage: %s <valid_path>\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    if((fd = open(argv[1], O_RDONLY, 0)) == -1){
        fprintf(stderr, "Fatal error wihile opening the file.\n");
        exit(EXIT_FAILURE);
    }

    len = flen(fd);
    printf("%d\n", len);

    exit(0);
}

I think the problem could be related with EOF in the for loop condition. But if this is true, how can I know when the file actually ends?

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

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

发布评论

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

评论(1

沩ん囻菔务 2025-01-24 01:15:34

您应该测试 read 的返回值。

返回值:读取的字节数
如果函数尝试读取文件末尾,则返回 0。
如果允许继续执行,则该函数返回 -1。

long long flen(int file) {
    long long i = 0;
    char c;
    while(read(file, &c, 1) == 1) {
        i++;
    }
    return i;
}

另外:您的类型与 int flen()long long len 不匹配。

You should test the return value from read instead.

Return Value: the number of bytes read
If the function tries to read at end of file, it returns 0.
If execution is allowed to continue, the function returns -1.

long long flen(int file) {
    long long i = 0;
    char c;
    while(read(file, &c, 1) == 1) {
        i++;
    }
    return i;
}

Aside: you have a type mismatch with int flen() and long long len.

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