c - 从文件读取的意外输出
问题描述
我有一个要阅读的文本文件。该文件具有以下内容:
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'
字符有关,但我找不到错误。
另外我想问一下是否有办法让它更优雅。
解决方案
至少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'
// aux.name[strlen(aux.name) - 1] = '\0';
aux.name[strcspn(aux.name, "\n")] = '\0';
推荐阅读
- javascript - 编译失败(反应 javascript)
- python - 在 discord.py 中访问成员的横幅
- wordpress - Woocommerce:如何将自定义 meta_key 添加到结帐 billing_phone?
- python - 我的程序在编写过程中卡住了
- sympy - Sympy中绝对值周期函数的临界点
- python - 获取 TypeError:'int' 对象不可迭代尝试将项目附加到列表
- javascript - 我可以使用 v8(-debug) 执行 Ignition 生成的字节码吗?
- npm - NPM 是否仅适用于开源?
- c# - 如何在.net core 中动态生成 DbSet?
- android - 在片段中滑动并删除