c - 将结构写入文件,给出垃圾值

标签 c file structure fwrite garbage

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

   #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/

相关文章:

javascript - 使用 AngularJS 加载动态指令 - 错误 : Access to restricted URI denied

c - fgets 将字符串添加到另一个变量

c++ - 将资源文件与应用程序链接?

c - 如何将字符串的一部分复制到结构数组的元素中?

c# - 如何检测文件夹是否复制完成?

file - 您可以在 Outlook 以外的任何软件中创建常用文件吗?

c++ - 在 C++ 中将值复制到结构成员和从成员复制值

c - "variable"使用 C 预处理器进行长度初始化

c - int c 与 c == "\n"和 c = =""冲突?

c 程序将 show 命令输出存储到字符串中