【发布时间】:2021-06-05 06:16:48
【问题描述】:
所以我编写了一个程序,它将接收有关 DVD 的信息 (具体来说,它是 位置、IDkey(只是一些随机数)Title、Genre 和 Year of release),并使用结构将这些信息写入名为 的 .txt 文件“person.txt”。我很肯定我的代码大部分都可以工作,但是当我去测试它时,.txt 文件中收到的输出是用一些奇怪的符号语言而不是英语编写的,坦率地说,我不知道为什么会这样。任何关于为什么会发生这种情况的解释将不胜感激,谢谢:)
计划
#include <stdio.h>
#include <stdlib.h>
// a struct to read and write
struct dvd
{
int fposition;
int fIdKey;
char ftitle[50];
char fgenre[50];
int fyear;
};
int main ()
{
FILE *outfile;
struct dvd input;
// open file for writing
outfile = fopen ("person.txt", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
printf("Postion: ");
scanf("%d", &input.fposition);
printf("ID Key: ");
scanf("%d", &input.fIdKey);
printf("Title: ");
scanf("%s",&input.ftitle);
printf("Genre: ");
scanf("%s", &input.fgenre);
printf("Year: ");
scanf("%d", &input.fyear);
// write struct to file
fwrite (&input, sizeof(struct dvd), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
return 0;
}
【问题讨论】:
-
您希望输出文件中究竟是什么?您是否了解您正在将原始二进制(内存中表示)结构直接写入文件,而不是以任何方式对其进行序列化?
-
@JonathonReinhart 好吧,我只是在尝试编写用户输入的数据(IdKey、标题等),而您对它进行专门化究竟是什么意思?
-
我接触 C 已经 20 多年了,但看起来你看到的垃圾只是每个字段的最后一次用户输入之后的 char 数组的内容。鉴于您没有覆盖它,它实际上包含在字符数组中,因此由 fwrite 写入。即,如果您允许 50 个字符并且用户输入“a”(不带引号),那么它应该写一个 + 49 个字符的垃圾(可能减去 1-2 个字符来解释字符串终止符 \0,但要注意这一点) .
-
对不起,我的意思是“序列化”(该死的自动更正)。
-
@ApplePie 作为一种预防措施,我将其声明为 50 个字符,因为我不完全知道用户输入的标题或类型的长度,但如果这是导致问题的原因,我'将看看它并尝试解决一些问题
标签: c file struct file-writing