首页 > 解决方案 > 从文件读取的意外输出

问题描述

我有一个要阅读的文本文件。该文件具有以下内容:

Asdsf adsfsd
54
asdfa adwfasd
12
asdf adf 
545
asdf asdfasfd
3243
adfasf asdfasdf
324324
asfda asdfasdf
3124
adfa asdfas
432
asdf ad

和我的代码:

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


struct Element {
    int edad;
    char name[50];
};

int main() {
    struct Element aux;
    FILE* fitxer;
    fopen_s(&fitxer, "Text.txt", "r");
    if (fitxer != NULL) {
        while (!feof(fitxer)) {
            fgets(aux.name, 50, fitxer);
            aux.name[strlen(aux.name) - 1] = '\0';
            int ret = fscanf_s(fitxer, "%i", &aux.edad);
            char endl;
            fscanf_s(fitxer, "%c", &endl);
            printf("%d %s \n", aux.edad, aux.name);
        }
        fclose(fitxer);
    }
    else {
        printf("Error: File not found.");
    }    
}

我之前遇到过问题,因为我不知道那f_scanf不带结束符。现在的问题是文件中有一些字符串被截断了。输出:

54 Asdsf adsfsd
12 asdfa adwfasd
545 asdf adf
3243 asdf asdfasfd
324324 adfasf asdfasdf
3124 asfda asdfasdf
432 adfa asdfas
432 asdf a

例如,在这个例子中,最后一个字母被切掉了。我怀疑它与转换为字符串、添加'\0'字符有关,但我找不到错误。

另外我想问一下是否有办法让它更优雅。

标签: cfgets

解决方案


至少3个问题:

错误的文件结尾测试,避免幻数

参考

//while (!feof(fitxer)) {
//    fgets(aux.name, 50, fitxer);
while (fgets(aux.name, sizeof aux.name, fitxer)) {

fscanf_s(fitxer, "%c", &endl);缺少一个增强。

fscanf_s()如果有兴趣或更好的研究,只需fgets()用于输入。

错误的代码终止了潜在的试验'\n'

替代品: 1 2

// aux.name[strlen(aux.name) - 1] = '\0';
aux.name[strcspn(aux.name, "\n")] = '\0';

推荐阅读