在c中写入和读取文件

writing and reading from a file in c

我想做的是编写 2 个函数: 一个写入文件的函数和一个读取同一文件的函数...... 我面临两个问题: 1-当我同时执行这两个功能时: 第一个函数几乎可以正常工作,但没有 return 1 ;第二个函数正确读取了我的文件,但在无限系列的 0 之后它给了我。 2-当我只执行第二个函数(读取)时,它给我无限系列的 0,它没有读取我在文件中的内容。

#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
 struct Product
    {
        int Code;
        char Name[30];
        float Price;

    };
    struct Product p[15];

int SaveProduct(int n) // n number of product
{
    int i;
     FILE *f;
     if((f=fopen("save.txt","w"))==NULL)

     {
         return 0;
     }
     else{
     fprintf(f,"Code\tName\tPrice\n");


     for(i=0;i<n;i++)
     {
        printf("enter Code,Name,Price\n");
      scanf("%d %s %f",&p[i].Code, p[i].Name,&p[i].Price);
      fprintf(f,"%d \t %s\t %.2f\n",p[i].Code, p[i].Name,p[i].Price);
     }
     fclose(f);
        return 1;
     }
}
void displayProduct()
    {

        FILE *f;
        if ( (f=fopen("save.txt","r"))==NULL )
        {
            printf("error");
        }
        else
        {int i=0;
            printf("Code\tName\tPrice\n");
           while(fscanf(f,"%d %s %f",&p[i].Code,p[i].Name,&p[i].Price) != EOF)

             {

                printf("%d\t %s\t %.2f\n",p[i].Code,p[i].Name,p[i].Price);
                i++;
                }

            fclose(f);
        }

    }





int main()

{

    SaveProduct(3);  //3 number of product
      displayProduct();


}

只需删除该行并再次 运行 :)

fprintf(f,"Code\tName\tPrice\n");

上面的行导致输出到 save.txt 文件,如下所示 -

Code Name Price    // line 1
123  aa   10       // line 2
456  bb   20       // line 3
789  cc   30       // line 4

当程序使用

读取文件时
fscanf(f,"%d %s %f",&p[i].Code,p[i].Name,&p[i].Price)

第 1 行的输入错误。这就是为什么应该删除 SaveProduct 函数中的上述代码,这样 第 1 行 就不会写入文件中。

这是对您的问题 2) 的部分回答,为什么第二个函数,即 displayProduct,会给出无限系列的 0...?

至少有两个问题:

a) 为什么它得到 0?

正如@Abdullah Al Masud Tushar 已经回答的那样,正在读取的文件 save.txt 的第一行是 Code<TAB>Name<TAB>Price,而 fscanf 的格式字符串是 "%d %s %f" . %d 预计:

Any number of decimal digits (0-9), optionally preceded by a sign (+ or -).

但满足'C',然后fscanf停止不填充任何项目和returns,保持项目不变。并且,您的结构数组 p 是全局变量并被初始化为全零。

b) 为什么是无限的? fscanf returns条正常填写成功的条数;它 returns EOF 仅当发生错误或到达文件末尾时才能成功读取任何数据。

在您的情况下,由于问题 a) 的原因,返回零并且条件 fscanf(...) != EOF 始终为真。

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

同样,fscanf还有一些额外的问题:

c) 在文件中,'\t' 用作字段分隔符(写入时),但在 fscanf 的格式字符串中使用空白 space (' ') ,因此应为空白 space。

d) %s 需要任意数量的非白色 space 字符,在找到的第一个白色 space 字符处停止。如果“name”输入包含whitespace,则无法正确填写,更有什者会混淆后面的%f.

请参阅 fscanf 的手册,网址为 http://www.cplusplus.com/reference/cstdio/fscanf/ 要么 http://man7.org/linux/man-pages/man3/fscanf.3.html