c - 具有字符串的结构中的 fscanf

标签 c string malloc structure scanf

我的代码有问题。
我想fscanf result.txt到结构体,但是不行;

结果.txt格式:

point name (for examples)
623   john
457   peter
312   chuck
etc.

首先我计算行数,然后我malloc。对于结构的字符串,我必须再次 malloc,但我不知道字符串的长度。所以我在 for 循环中计算它。

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

typedef struct ranklist {
   int point;
   char* name;
} ranklist;

int how_many_lines (FILE *fp){

   rewind(fp);

   int ch;
   int line=0;

   while (EOF != (ch = fgetc(fp)))
       if (ch=='\n')
          ++line;

   rewind(fp);

   return line+1;
}

int how_many_letter(FILE *fp){

   int ch;
   int letter = 0;
   int space=0;

   while ('\n' != (ch = fgetc(fp)))
       if (ch==' ')
           space=1;
       if (space == 1)
           letter++;

   return letter;
}

int main()
{
    FILE *fp;
    int y;
    int name_length;

    ranklist** r;

    fp = fopen("result.txt","r");

    int lines;
    lines = how_many_lines(fp);


    r = (ranklist**) malloc(lines * sizeof(ranklist*));
    for (y = 0; y < lines; ++y){
       name_length = how_many_letter(fp);
       r[y] = (ranklist*) malloc(name_length * sizeof(ranklist));
    }

    for(y = 0; y < lines; y++){
       fscanf(fp,"%d %s", &(r[y]->point), r[y]->name);
    }

    for( y = 0; y < lines; y++){
        printf("%d %s", (r[y]->point), r[y]->name);
    }


    for (y = 0; y < lines; ++y)
       free(r[y]);
    free(r);

    fclose(fp);

   return 0;
}

最佳答案

修复样本

int how_many_records(FILE *fp){
    char ch;
    int line=0;
    int status;

    rewind(fp);
    while((status=fscanf(fp, "%*d %*[^\n]%c", &ch))==1)
        ++line;
    if(status != EOF){
        ++line;
    }
    rewind(fp);

    return line;
}

int how_many_letter(FILE *fp){
    int letter = 0;
    long pos = ftell(fp);

    //fscanf(fp, " %*[^\n]%n", &letter);
    fscanf(fp, " %*s%n", &letter);
    fseek(fp, pos, SEEK_SET);

    return letter;
}

int main(void){
    FILE *fp = fopen("result.txt","r");
    int y;
    int name_length;
    int lines = how_many_records(fp);
    ranklist *r = malloc(lines * sizeof(*r));//just pointer, Do not need double pointer

    for (y = 0; y < lines; ++y){
        fscanf(fp, "%d", &r[y].point);
        name_length = how_many_letter(fp);
        r[y].name = malloc(name_length + 1);
        fscanf(fp,"%s", r[y].name);
    }
    fclose(fp);

    for( y = 0; y < lines; y++){
        printf("%d %s\n", r[y].point, r[y].name);
        free(r[y].name);
    }
    free(r);

    return 0;
}

关于c - 具有字符串的结构中的 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258439/

相关文章:

c++ - 'dxerr9.h' : No such file or directory

c - 如何将 typedef 结构转换为 uint8_t 参数

c# - 如何将 xml 字符串读入 XMLTextReader 类型

带有 N 个前导零的 C printf

c - C中的字符增量

python - 元组列表(从元组中删除特殊项目)

C 编程、分段故障核心转储

c - 数组的最大大小 - 段错误

c - 结构尺寸

转换为 C 中宏内部的非标量错误