簡體   English   中英

Fscanf 從文件中間讀取 C

[英]Fscanf Reading From Middle of File C

我正在創建一個程序,它從文件中讀取數字,獲取數字的數量,創建一個數組並顯示這些數字以及文件中的數字數量。 我正在使用 fscanf 從文件中獲取數據。 我終於得到了要編譯的程序和 output 但它只讀取了文件中 10 個數字中的 4 個。 如果我增加數字的數量,它仍然只讀取 4 個數字。 如果我將數字數量減少到 4 以下,它仍然會嘗試讀取 4 個數字並打印 memory 中的隨機數。我認為這是一個指針問題,但我還是新手,並不完全理解指針。 感謝幫助。

代碼:

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

int ReadSize (FILE*);
void readData(FILE* fp, int size, int* arr1);
int* allocateMemory(int);

int main (int argc, char* argv[])
{
    FILE * in = fopen(argv[1], "r"); //Gets file to read
    int size = ReadSize(in);

    printf("Size: %i\n", size); //Temp Line to Print Size

    int *arr1 = allocateMemory(size);
    readData(in, size, arr1);

    printf("Data: ");

    for (int i = 0; i < size; i++)
    {
        printf("%d, ", arr1[i]);
    }
}

int ReadSize(FILE* fp)
{
    int size = 0;
    fscanf(fp, "%d", &size);
    return size;
}

void readData(FILE* fp, int size, int* arr1)
{
  int i;

  for(i = 0; i < size; i++)
  {
      fscanf(fp, "%d", &arr1[i]);
  }
}

int* allocateMemory(int sz)
{
  int *temp = (int*)malloc(sizeof(int)*sz);
  return temp;
}

輸入文件:

4 2
-1 2 
1 2
2 -1
-1 -2

我認為你誤解了文件格式。 您從文件中讀取“4”,然后循環迭代 4 次:因此是 4 個數字,而不是 10 個。

但我們只能猜測您應該閱讀什么。

也許是這樣的:

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

int main (int argc, char* argv[])
{
    FILE *in;
    if ((fp = fopen(argv[1], "r")) == 0) {
      printf("Error: unable to open file!\n");
      return -1;
    }

    int nitems, items_per_line;
    if (fscanf(fp, "%d %d", &nitems, &items_per_line) != 2) {
       printf ("Error reading dimensions!\n");
       return -1;
    }

    int *arr1 = malloc (sizeof(int) * nitems * items_per_line);
    if (arr1 == 0) {
      printf("Error: unable to malloc array!\n");
       return 1;
    }
    for (int i = 0; i < nitems * items_per_line; i++) {
       fscanf(fp, "%d", &arr1[i]);
    }

    return 0;
}

或者也許您最好使用 n 維數組(例如 arr1[2][4])?

再次 - 在不知道更多關於格式的情況下,我們只能猜測......

PS:您應該始終檢查代碼中的錯誤!

您的程序所做的第一件事是嘗試從ReadSize()中的文件中讀取一個十進制數。 那得到4 ,然后,正如您所描述的,讀取 4 個數字。 如果您希望它與程序期望的格式相匹配,您需要在輸入文件的頂部放置一個10

暫無
暫無

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

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