问题描述
所以我编写了一个程序来接收有关 DVD 的信息(具体来说是位置、IDkey(只是一些随机数)Title、流派和发布年份),并使用结构体将该信息写入名为 的 .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;
}
解决方法
您正在将这些值写入文件:
int fposition;
int fIdKey;
char ftitle[50];
char fgenre[50];
int fyear;
但是您将整个文件显示为字符。这种对 ftitle
和 fgenre
有效,因为它们确实是字符……尽管由于您没有填充所有 50 个字符,因此也会显示一些丑陋的未初始化字符。这很容易解决:只需在写入文件之前用一些已知字符(例如空格)填充未使用的字符(以及空终止符),或者根本不写入未使用的字符。您可以使用 strlen()
查找每个字符串的长度,并使用 memset()
将未使用的字符设置为可打印的已知字符。
接下来,保存 int
并将其作为文本阅读是有问题的。您需要决定一种格式。要么像现在一样写成整数,然后读成整数(这意味着您需要一个特殊的程序来读取文件),要么承诺只将文本写入文件。
最简单的方法可能是只将文本写入文件。您可以使用 fprintf()
代替 fwrite()
。您也可以将 fprintf()
用于字符数组,它会自动仅将每个字符串的“已使用”部分写入空终止符,跳过所有“垃圾”字符。