【问题标题】:Writing a structure to file giving garbage value将结构写入文件以提供垃圾值
【发布时间】:2014-12-10 07:17:19
【问题描述】:

您好,我正在尝试将结构写入文件。 下面是代码。

   #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);
    }

输出:

苏米亚0000^@

如何去掉最后一个字符?

【问题讨论】:

  • 另外,对于人类可读的输出,最好使用fprintf() 而不是fwrite()
  • 我想写整个结构,而不是单个成员。 fprintf 可以吗?
  • 在此之前,请告诉我们,这是什么if(fout=fopen("output.txt","w"))?你知道你在做什么吗?
  • 您的代码无法编译。请向我们展示实际代码。
  • @Sourav fopen 没有返回值吗?该值将用于评估“如果”

标签: c file structure fwrite garbage


【解决方案1】:

由于您将整个结构写入文件,因此需要避免填充。这可以通过这种方式完成:

#pragma pack(push)
#pragma pack(1)
     struct student
        {
         char name[10];
         char space[1];
         char rollno[5];
        }head_rec;
#pragma pack(pop)

您的 main 函数还必须返回一个 integer 值。所以把void main()改成int main()

另外一点:使用snprintf 而不是sprintf,这样您就可以指定目标缓冲区的最大大小,这样更安全。

加号:

if(fout=fopen("output.txt","w"))

应该是:

 if((fout=fopen("output.txt","w"))==NULL)

【讨论】:

  • 感谢您的帮助。但这对我不起作用。 :(
  • @SoumyaSaraswataDash 如果你想写一个structchar arrays,你需要避免在字符数组末尾出现空字符!否则它将被写入文件。您还需要确保每个数组都与您要存储的字符数一样大。因此,在 10 字节长的名称中存储“SOUMAYA”将不起作用,因为终止空字符后面的字节是未定义的。所以“SOUMAYA”必须存储在一个正好为 7 个字节的数组中。但是,我建议使用类似的东西:(待续)...
  • snprintf(temp,sizeof(temp),"%s%s%s",head_rec.name,head_rec.space,head_rec.rollno);fwrite(temp,1,strlen(temp),fout); 别忘了fclose(fout);fout=NULL;
猜你喜欢
  • 2022-08-18
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
相关资源
最近更新 更多