繁体   English   中英

使用C从文件读取数据

[英]Reading data from a file with C

我正在尝试使用C从文件读取数据。

这是文件(text.txt)的样子:

element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7

在下面,您可以看到我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void read_txt(){
    FILE *fp;
    char buf[100];
    size_t bytes_read;

    fp = fopen("text.txt", "a");

    if (fp == NULL) {
        printf("File couldn't be opened properly.");
        exit(1);
    }

    bytes_read = fread(buf, sizeof(buf), 1, fp);

    printf("%zu\n", bytes_read);
    printf("%s\n", buf);

    fclose(fp);
}


int main(void)
{
    read_txt();
    return 0;
}

不幸的是,我得到的只是以下内容:

0
h
Program ended with exit code: 0

为了实现我的目标(读取并打印文件中的所有数据),使用fread的正确方法是什么?

您对fread使用看起来还fread 但是,您应该使用"r"而不是"a"打开文件。 当您使用"a"打开文件时,流位于文件的末尾而不是开头。 当然,您必须循环读取文件,因为文件包含100个以上的字符

fp = fopen("text.txt", "a");
change to
fp = fopen("text.txt", "r");

返回值成功时,fread()和fwrite()返回读取或写入的项目数。 该数字等于仅在size为1时传输的字节数。如果发生错误或到达文件末尾,则返回值为短项计数(或零)。

我不知道是否应该向您指出常见问题解答,但是这个问题经常出现,解决方案几乎总是采用以下形式:

static const int M = 3; // For example.
int nread = -1;
int a = -1, b = -1, c = -1;

while ( M == ( nread = scanf( "%d %d %d", &a, &b, &c ) ) )
  do_stuff_with( a, b, c );

// Check why the last call failed.
// Was it due to feof(stdin) with 0 == nread, or did something go wrong?

如果没有,正确的做法通常是使用以下命令读取二进制格式的块:

sometype buffer[M];
while ( M == fread( buffer, sizeof(sometype), M, stdin ) )
  do_stuff_with( M, buffer );

请注意,您正在将sizecount参数反转为fread() ,尽管它可能仍然可以工作。

有时,人们想要做的是使用fgets()而不是 gets() !)读取一行,然后使用sscanf()对其进行解析。

太复杂的东西可能需要一个正则表达式库或解析器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM