簡體   English   中英

在文件 C 中構造 fscanf

[英]Struct fscanf in file C

在文件中,我需要讀取一些輸入:

這是一個例子:

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 的最后一行顯示了一些隨機數。

我使用 printf 的最后一行顯示了一些隨機數。 ...

您看到的隨機數是因為尚未正確填充要打印的緩沖區。

此示例顯示如何讀取文件,使用fgets()讀取行緩沖區,然后使用sscanf()解析行中的前兩個值。 (閱讀代碼中的注釋以獲取其他一些提示。)

   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;
    }

同意最好使用 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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM