【问题标题】:Struct fscanf in file C在文件 C 中构造 fscanf
【发布时间】:2020-06-24 12:23:19
【问题描述】:

在文件中我需要读取一些输入:

这是一个例子:

8 15
[1,1] v=5 s=4#o
[4,2] v=1 s=9#x
typedef struct{

    int red2;
    int stupac2;
    int visina;
    int sirina;
    char boja[10];

}Tunel;

FILE* fin = fopen("farbanje.txt", "r");
Tunel* tuneli = malloc(sizeof(Tunel)*50);
//    if(fin!=0)
fscanf(fin,"%d %d", &r,&s);
printf("%d %d", r,s);

int p=0;


while (fscanf(fin, "[%d,%d]", &tuneli[p].red2, &tuneli[p].stupac2) == 2)
{

    p++;
}

for(i=0;i<p;i++)
{
    printf("[%d,%d]", tuneli[i].red2, tuneli[i].stupac2);
}

问题是它不会从这里正确读取我的输入:[1,1] v=5 s=4#o 我使用 printf 的最后一行显示了一些随机数。

【问题讨论】:

  • 上面的例子是你正在阅读的文件的内容吗?如果您想从文件中读取int,则必须先进行一些解析,以将数字与其他字符分开。
  • 你可能想使用一些JSON库,也许是jansson

标签: c arrays file


【解决方案1】:

同意最好使用 fgets 但是,如果您想继续使用当前的方法,

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

typedef struct{
  int red2;
  int stupac2;
  int visina;
  int sirina;
  char boja[10];
}Tunel;


int main(){
  int r, s, i;
  FILE*fin=fopen("farbanje.txt", "r");
  if(fin==NULL) {
    printf("error reading file\n");
    return 1;
  }
  Tunel *tuneli=(Tunel*)malloc(sizeof(Tunel)*50);
  fscanf(fin,"%d %d\n", &r,&s);
  printf("%d %d", r,s);

  int p=0;

  while (fscanf(fin, " [%d,%d]%*[^\n]", &tuneli[p].red2, &tuneli[p].stupac2) == 2)
  {
    p++;
  }

  fclose(fin);

  for(i=0;i<p;i++)
  {
    printf("[%d,%d]", tuneli[i].red2, tuneli[i].stupac2);
  }
}

【讨论】:

    【解决方案2】:

    我使用 printf 的最后一行显示了一些随机数。...

    您看到的随机数是因为尚未正确填充要打印的缓冲区。

    此示例显示如何读取文件,使用fgets() 读取行缓冲区,然后使用sscanf() 解析行中的前两个值。 (阅读代码中的 cmets 以了解其他一些提示。)

       int main(void)//minimum signature for main includes 'void'
        {
            int r = 0;
            int s = 0;
            char line[80] = {0};//{initializer for arrays}
            int p = 0;
            Tunel *tuneli = malloc(sizeof(*tuneli)*50);
            if(tuneli)//always test return of malloc before using it
            {       
                FILE *fin = fopen(".\\farbanje.txt", "r");
                if(fin)//always test return of fopen before using it
                {
                    fgets(line, sizeof(line), fin);
                    sscanf(line, "%d %d", &r, &s);
                    while(fgets(line, sizeof(line), fin))
                    {
                        sscanf(line, " [%d,%d]", &tuneli[p].red2, &tuneli[p].stupac2);
                        //note space  ^ here to read only visible characters
                        printf("[%d,%d]\n", tuneli[p].red2, tuneli[p].stupac2);//content is now populated corretly
                        p++;
                    }
                    fclose(fin);//close when finished
                }
                free(tuneli);//free when done to prevent memory leaks
            }
            return 0;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多