嗨,我正在尝试将结构写入文件。 下面是代码。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/*structure*/
struct student
{
char name[10];
char space[1];
char rollno[5];
}head_rec;
/*main*/
void main()
{
FILE *fout;
if(fout=fopen("output.txt","w")==NULL)
{
printf("Cannot open the file to write");
exit;
}
memset(&head_rec,'\0',sizeof(struct student);
sprint(head_rec.name,"SOUMYA",6);
memset(head_rec.space,' ',1);
memset(head_rec.rollno,'\0',sizeof(head_rec.rollno);
sprint(head_rec.rollno,"0000",4);
head_rec.rollno[4]='\0';
fwrite(&head_rec,sizeof(struct student),1,fout);
}
输出:
SOUMYA 0000^@
如何去掉最后一个字符?
最佳答案
由于您要将整个结构写入文件,因此需要避免填充。这可以通过以下方式完成:
#pragma pack(push)
#pragma pack(1)
struct student
{
char name[10];
char space[1];
char rollno[5];
}head_rec;
#pragma pack(pop)
此外,您的主函数必须返回一个整数
值。因此将 void main()
更改为 int main()
另外一点:使用 snprintf
而不是 sprintf
,这样您就可以指定目标缓冲区的最大大小,这使其更安全。
加上:
if(fout=fopen("output.txt","w"))
应该是:
if((fout=fopen("output.txt","w"))==NULL)
关于c - 将结构写入文件,给出垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27395266/