写入正常
fprintf(fp, "%d\t%s\t%s\t%s\t%d\n", p->data.ID, p->data.naem, p->data.writer,
p->data.press, p->data.monovalent);
读出乱码
fscanf_s(fp,"%d\t%s\t%s\t%s\t%d\n",p->data.ID,p->data.naem,p->data.writer,p-
data.press,p->data.monovalent);
求解:fscanf_s正确用法
编译器:Visual Studio2022
p->data 的成员类型是什么?如果不是 字符数组,要加上 &
的哦
请看这个帖子下面的 “相关推荐”
不知道你这个问题是否已经解决, 如果还没有解决的话:/*
a.txt:
1 2 3 0.4
2 3 4 0.5
*/ code如下:
# include <stdlib.h>
# include <stdio.h>
int main()
{
FILE* file;
char path[] = "./a.txt";
file = fopen(path,"r");
int a, b, c;
float d;
while (fscanf(file, "%d %d %d %f", &a, &b, &c, &d) == 4)
{
printf("%d %d %d %f\n", a, b, c, d);
}
return 0;
}
/*
output:
1 2 3 0.400000
2 3 4 0.500000
*/ code如下
问题回答:
针对第一个代码段,可以通过以下步骤读取txt文件并且不出现乱码:
1.使用fopen打开文件,以'r'模式打开;
2.使用fscanf_s按照指定的格式读取文件内容,可以根据需求选择使用int、float或double等数据类型来读取文件,具体用法可参考参考资料;
3.注意使用fclose关闭文件指针。
以下是具体代码示例:
#include <stdio.h>
int main()
{
FILE* fp;
errno_t err;
int a, b, c;
float d;
/*打开文件*/
err = fopen_s(&fp, "./a.txt", "r");
if (err != 0)
{
perror("文件打开失败");
return err;
}
/*读取文件内容*/
while (fscanf_s(fp, "%d %d %d %f", &a, &b, &c, &d) == 4)
{
printf("%d %d %d %f\n", a, b, c, d);
}
/*关闭文件指针*/
fclose(fp);
return 0;
}
针对第二个代码段,可以这样使用fscanf_s函数正确读取txt文件并且不出现乱码:
1.使用fopen打开文件,以'r'模式打开;
2.使用fscanf_s按照指定的格式读取文件内容,注意指定读取字符串时的格式为"%[^,],%[^,],%s",可参考参考资料中的解释;
3.注意使用fclose关闭文件指针。
以下是具体代码示例:
#include <stdio.h>
int main()
{
FILE* fp;
errno_t err;
char Name[20];
char Time[20];
char Action[20];
/*打开文件*/
err = fopen_s(&fp, "C:\\Users\\20805687\\Desktop\\a.txt", "r");
if (err != 0)
{
perror("文件打开失败");
return err;
}
/*读取文件内容*/
while (fscanf_s(fp, "%19[^,],%19[^,],%s", Name, Time, Action) == 3)
{
printf("%s %s %s\n", Name, Time, Action);
}
/*关闭文件指针*/
fclose(fp);
return 0;
}
注意:以上提供的代码仅供参考,需要根据实际情况进行修改,如文件路径等。
如果出现错误,可以使用perror函数输出错误信息以便定位问题。