如何存储和读取文件中的数据 [英] how to store and read data from files

查看:64
本文介绍了如何存储和读取文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Linux中C语言的新手.我正在尝试将数据存储到文件并读回.这是正确的方法吗?当我尝试编译此文件时,出现错误.谁能帮我.预先感谢.

I am new to C in linux. I am trying to store data to file and read them back. Is this the correct way. When I try to compile this i am getting errors. Can anyone help me please. thanks in advance.

 #include<stdio.h>
       typedef struct
    {
      int select;
      char lastname[25];
      char firstname[25];
      char address[25];
      char phonenumber[25];
    } addressbook;

    addressbook a[5];
     FILE *fp;
    int main()
    {
      int i;

     for( i=0; i<5 ; i++)
    {
     printf("enter details\n");
       printf("enter lastname:\n");
       scanf("%s", a[i].lastname);
       printf("enter firstname:\n");
       scanf("%s", a[i].firstname);
       printf("enter address:\n");
       scanf("%s", a[i].address);
       printf("enter phone number:\n");
       scanf("%s", a[i].phonenumber);
      fp = fopen("addressbook.dat","a+");
      fwrite(&a, sizeof(a), 1, fp);
      fclose(fp);
    }

    for(i=0; i<5; i++)
    {
      fopen("addressbook.dat", "r");
      fread(&a, sizeof(a), 1, fp );
      printf("lastname:%s\n", a[i].lastname);
      printf("firstname:%s\n", a[i].firstname);
      printf("address:%s\n", a[i].address);
      printf("phonenumber:%s\n", a[i].phonenumber);
      fclose(fp);
    }
    return 0;
    }

我没有得到任何输出.它是空白.

i am not getting any output. it was blank.

推荐答案

查看此代码,然后让我向您解释代码中所有错误的地方.

Check out this code, and let me explain you what all was wrong in your code.

    #include<stdio.h>

    typedef struct
    {
          int select;
          char lastname[25];
          char firstname[25];
          char address[25];
          char phonenumber[25];
    } addressbook;

    #define ARRAYLEN 2

    addressbook a[ARRAYLEN];
    FILE *fp;

    int main()
    {
         int i;

         fp = fopen("addressbook.dat","a+");

         for( i=0; i<ARRAYLEN ; i++)
         {
           printf("enter details\n");
           printf("enter lastname:\n");
           scanf("%s", a[i].lastname);
           printf("enter firstname:\n");
           scanf("%s", a[i].firstname);
           printf("enter address:\n");
           scanf("%s", a[i].address);
           printf("enter phone number:\n");
           scanf("%s", a[i].phonenumber);
           fwrite(&a[i], sizeof(a), 1, fp); /* notice, array indexed */
        }
        fclose(fp);

        fopen("addressbook.dat", "r");
        for(i=0; i<ARRAYLEN; i++)
        {
          fread(&a[i], sizeof(a), 1, fp );
          printf("lastname:%s\n", a[i].lastname);
          printf("firstname:%s\n", a[i].firstname);
          printf("address:%s\n", a[i].address);
          printf("phonenumber:%s\n", a[i].phonenumber);
        }
        fclose(fp);

        return 0;
    }

实际上,您的代码按原样(除了已经完成的编辑)并不是很不正确,但是它有一些小而关键的缺陷.

Actually, your code as-is (apart from the edit you've already done) isn't so incorrect, but it had some small yet crucial flaws.

  1. 唯一真正的变化是:-

  1. The only real change is this :-

fwrite(&a[i],...

fread(&a[i],...

即传递您要写入的特定数组元素的地址,而不是整个数组.另外,即使您要传递整个数组的地址,也不会.您要求库编写的字节/字符的大小仅为sizeof(thestructure),因此基本上其余部分都被截断了.否则,您要写入文件的内容将类似于...

i.e. pass the address of the particular array-element that you want to write, not the entire array. Also, even though you were passing address of the entire array, the no. of byte/characters you were asking library to write, was just sizeof(thestructure), so essentially the remaining was truncated. Without that, what you were writing into the file was something like...

A          <-- file contents after, first iteration
AAB        <-- file contents after, second iteration
AABABC     <-- file contents after, third iteration
AABABCABCD <-- file contents after, fourth iteration
....

我想您会发现这是怎么回事.另外,您的addressbook.dat的内容是文本,因此一个简单的"cat addressbook.dat"(在Linux上)会告诉您出了什么问题:-)

I think you'd figure out from that, what was wrong. Also the contents of your addressbook.dat was text, so a simple "cat addressbook.dat" (on Linux) would have told you what was wrong :-)

您将在每次迭代中打开和关闭文件.现在这不是一个错误,而只是次优的事情,很可能是您不想做的事情.文件操作成本很高,而打开/关闭这些操作会花费大量的CPU周期.您最好将所有写入操作一次打开文件,然后将其读取一次打开文件.(当然,只需将文件指针指向文件的开头,一次就可以删除在写块之后完成的fclose()和在读块之前完成的fopen(),作为练习).

You are opening and closing file in every iteration. Now this is not an error, but just a sub-optimal thing, and quite likely to be something you do not want to do. File operations are costly, and opening/closing those cost quite a few CPU cycles. You are better off, opening file once for all writes, and once for reads. (Of course, once can remove the fclose() done after write-block and fopen() done before read-block as well, by just getting the file-pointer to the beginning of file -- left as an exercise for you).

在测试时,没有人愿意输入这么多数据.因此,我添加了一个#define(使用更新的编译器,您也可以将其替换为const定义),该定义了一个宏,该宏保存通讯录数组的大小.为了进行测试,我将其保持为"2".对于生产,您可以将该值更改为"1000",它将仍然有效.同样,如果您愿意,这不是错误,只是更好的样式.

While testing, no one wants to enter so much data. So I've added a #define (and with a newer compiler you can replace it with a const definition as well), that defines a macro which holds the addressbook array size. For testing, I keep it at "2". For production you can just change that value to "1000" and it will still work. Again, this wasn't an error, just a better style, if you will.

哦,顺便说一句,请确保您的缩进正确.您来自Python世界吗?也可能是SO张贴代码块所需缩进的产物.

Oh, and BTW, pls get your indentation right. Are you coming from Python world ? Or it could be an artifact of the indentation required by SO for posting code-blocks.

HTH

这篇关于如何存储和读取文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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