逐行读取文件错误

Read line by line of file error

本文关键字:错误 文件 读取 逐行      更新时间:2023-10-16

我必须从文件中解析数据。该文件具有以下结构:

text1.txt 1
text2.txt 2
text3.txt 4

文件可以在这里下载我想要得到text1。txt和1。所以我的代码如下:

#include <stdio.h>
void main() 
{ 
FILE    *fp= NULL;
int     status= -1;
char    name[100];
char *filename="test.txt";
fp= ::fopen(filename, "rt");
if (!fp)
    {
        printf("Error open: "%s"nn", filename);
        return;
    }
do
{
int number=0;
status= fscanf(fp, "%s %d", name,number);
}
while (status!= EOF);
}

我正在使用c++。我的问题是它在

处崩溃了
status= fscanf(fp, "%s %d", name,number);

错误是"访问冲突写入位置0x00000000"。问题是什么?你能帮我吗?

通过地址传递要扫描的参数给fscanf:

fscanf(fp, "%s %d", name, &number);

编译器可能警告你:

warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]

你的代码有未定义的行为,这是你崩溃的根源。