简体   繁体   English

fgets和sscanf将文件读入数组

[英]fgets and sscanf to read file into an array

I am trying to implement a function that reads txt files that contain 2 double and int per line with a space as a delimiter, for example (data.txt): 我正在尝试实现一个函数,该函数读取每行包含2个double和int且带有空格作为分隔符的txt文件,例如(data.txt):

3.1 2.5 1 3.1 2.5 1

3.4 4.5 2 3.4 4.5 2

..... .....

I implemented the function below, it takes as arguments the file name, pointers to 2 double and an int. 我实现了下面的函数,它以文件名,指向2 double的指针和一个int作为参数。 Each pointer will be used to retrieve a column from the file. 每个指针将用于从文件中检索列。 I used fgets to get the line and then sscanf to extract the three values from the line. 我使用fgets来获取行,然后使用sscanf从行中提取三个值。 The program crushes at run time (error: Windows has triggered a breakpont in program.exe ) 程序在运行时崩溃(错误:Windows在program.exe中触发了breakpont)

... When I put a breaking point before returning from the main function the retrieved values are corrected but the program crushes when I hit continue. ...当我在从主函数返回之前设置一个断点时,检索到的值将被更正,但是当我点击继续时程序会崩溃。

To debug the function I added the following lines of code to the function ReadFile below: 为了调试该函数,我在下面的函数ReadFile中添加了以下代码行:

if (buf[strlen(buf)-1] != '\0') 
{ 
    putchar(buf[strlen(buf)-1]); //surprisingly this line prints 1 instead of a space... 
    exit(1);
}

With this change the code exit without reaching the end of the function. 进行此更改后,代码退出而未到达函数结尾。 I don't understand this because the buf variable is long enough to hold all the characters of one line from the sample file. 我不明白这一点,因为buf变量足够长,无法容纳示例文件中一行的所有字符。

I would appreciate your comments to fix this problem. 感谢您提出的解决此问题的意见。

Thank you. 谢谢。

bool ReadFile(const char* fileName, double* x, double* y, int* t, int size)
{
    FILE* fp;   
    char    buf[5000];
    fp = fopen( fileName, "r" );

    for( int i = 0; i < size && fgets(buf, 5000, fp) != NULL; i++)  
    {
        buf[strlen(buf)-1] = '\0'; 
        if (buf[strlen(buf)-2] != '\0') 
        {    
            putchar(buf[strlen(buf)-1]);//surprisingly this line prints 1 instead of a space...
            exit(1);       
        }

        sscanf(buf, "%lf %lf %d", &x[i], &y[i], &t[i]);


    }

    fclose(fp);
    return true;
}

问题出在调用者中,大小设置为1,而不是数据文件中的行数。

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

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