使用FWRITE()写一个结构到一个文件 [英] using fwrite() to write a struct to a file

查看:117
本文介绍了使用FWRITE()写一个结构到一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 100

typedef struct {int key; char data[MAXLEN];} record;

main(int argc, char *argv[])
{
    int n, i;
    record x;
    FILE *fp;
    fp = fopen(argv[1], "w+");
    printf("How many records will be entered? \n");
    scanf("%d", &n);
    for (i=0; i<n; i++)
    {
        printf("Enter record: \n");
        scanf("%d", &x.key);
        scanf("%s", &x.data);
        fwrite(&x, sizeof(record), 1, fp);
    }
}

我在做什么是创造用户输入记录,然后再存储这些记录到文件中。然而,当我使用FWRITE(),所创建的文件有很多写在这奇怪的字符,而不是简单地具有其密钥和数据的每个记录。谁能告诉我,为什么它写所有这些奇怪的字符?

What I am doing is creating records from user input, and then storing these "records" into a file. However, when I use fwrite(), the file that is created has a lot of strange characters written in it, instead of simply having each record with its key and data. Can anyone tell me why it's writing all of these strange characters?

推荐答案

有几个原因:


  1. 当你使用scanf函数,它转换人类可读的格式(%D)弄成电脑直接使用(INT)。那么你写出来的计算机可读的形式到一个文件中。现在,当您查看文件,您不使用逆电脑对人类可读的形式,但一些低得多的层次。这会给你的东西,看起来是错误的。

  2. 您正在写出来,即使你可能已经阅读部分数据到它整个x.data(比如,读一个字符串,长度10)。在该x.data的其余部分是初始化,并包含任何被保留在内存中的main()被调用时。

这篇关于使用FWRITE()写一个结构到一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆