如何使用fgets和sscanf将数据存储到文本文件中

时间:2018-04-20 15:54:15

标签: c pointers data-structures

我想要做的是获取一个文本文件并将4行存储到我的结构中,使用带有fgets和sscanf的循环来检索数据。

结构如下:

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #define SIZE 16
 #define N 4

struct Prova
{
    char nome[SIZE];
    int num;
};

现在我的功能看起来像这样:

void get_str(struct Prova * ptr){

FILE *f;
int i = 0;

 if(!(f = fopen(PATH,"r+")))
  {
    perror("Errore in apertura");
    exit(0);
  }

void * buffer = malloc(sizeof(struct Prova ));

  while(fgets(buffer,sizeof(struct Prova), f))
   {
    if(sscanf(buffer, "%s %d", (ptr+i)->nome, &(ptr+i)->num) > 0)
      {i++;}
   }

   free(buffer);
   fclose(f);
  }

更新:现在功能正常,谢谢大家。

主要功能是:

  int main()
  {
    struct Prova * ptr = malloc(N*sizeof(struct Prova));

    get_str(ptr);

    for(int i = 0; i< N; i++)
    {
      printf("\n%s %d", (ptr+i)->nome, (ptr+i)->num);
    }
   return 0;
  }

我试图阅读的文字文件是:

Pippo 4
Paperino 1
Topolino 3
Zio_paperone 2

1 个答案:

答案 0 :(得分:2)

正如其他人在评论中所建议的那样,检查sscanf()的返回值。此外,我不确定您传递给get_str()的论点。

同样在void * buffer = malloc(N*sizeof(struct Prova ));中,您无需为N structure分配内存,因为使用fgets()每次都会覆盖数据。它应该是void * buffer = malloc(2*sizeof(struct Prova ));

对于你提到的特殊情况,它可能是解决方案

while(fgets(buffer,sizeof(struct Prova), f)) {
       int ret = sscanf(buffer, "%s %d", (ptr+i)->nome, &(ptr+i)->num);
       printf("ret = %d\n",ret);
       printf("\n%s %d", (ptr+i)->nome, (ptr+i)->num);
       i++;
}

这是完整的代码

#define N 4
struct Prova {
        char nome[SIZE];
        int num;
};
void get_str(struct Prova * ptr) {
        FILE *f;
        if(!(f = fopen("data","r+"))) {
                perror("Error");
                exit(0);
        }
        void * buffer = malloc(2*sizeof(struct Prova ));/* Allocate 2* size, by considering Newline char & possible padding */ 
        int i =0;
        while(fgets(buffer,sizeof(struct Prova), f)) {
                int ret = sscanf(buffer, "%s %d", (ptr+i)->nome, &(ptr+i)->num);
                printf("ret = %d\n",ret);
                i++;
        }
        free(buffer);
        fclose(f);
}
int main() {
        struct Prova *v = malloc(N*sizeof(struct Prova));/* here you need to allocate 
                                for N structure, amke sure file have N lines of same format */
        get_str(v);
        for(int i =0;i<N;i++) {
                printf("\n%s %d\n",(v+i)->nome,(v+i)->num);
        }
        return 0;
}