读取大文件并将数据放置在正确的数组中,而不会太口头化

时间:2019-03-29 14:58:22

标签: c

所以我想做的是,我有两个文件,文件的大小为64x64,用空格和换行分隔。我想做的是读取文件并将其放在包含两个64x64数组的结构中。这些文件将如下所示:

2 5 1 6 2 ... 6 
3 2 9 5 1 ... 8 
. 
. 
2 4 1 5 2 ... 5

这就是我的想法

int
getFromFile(char *fileNameMatrixA, char *filenameMatrixB, struct Matrises *matrix)
{
  FILE *fileA, *fileB;
  char buffer[BUFFER_LEN];
  int counter = 0;

  if((fileA = fopen(fileNameMatrixA, "r")) == NULL)
    {
      return 1;
    }

  if((fileB = fopen(fileNameMatrixB, "r")) == NULL)
    {
      fclose(fileA);
      return 2;
    }

  while(fgets(buffer, sizeof(buffer), fileA) != NULL)
    {
      if(sscanf(buffer, "%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d", matrix->matrixA[counter][0], matrix->matrixA[counter][1], matrix->matrixA[counter][2], matrix->matrixA[counter][3], ... , matrix->matrixA[counter][63]) != 64)
    {
      fclose(fileA);
      fclose(fileB);
      return 3;
    }
      counter++;
    }

  counter = 0;

  while(fgets(buffer, sizeof(buffer), fileB) != NULL)
    {
      if(sscanf(buffer, "%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d\s%d", matrix->matrixB[counter][0], matrix->matrixB[counter][1], matrix->matrixB[counter][2], matrix->matrixB[counter][3], ... , matrix->matrixB[counter][63]) != 64)
    {
      fclose(fileA);
      fclose(fileB);
      return 4;
    }
      counter++;
    }

  fclose(fileA);
  fclose(fileB);
  return 0;
}

我认为大家都看到了问题。这绝不是解决问题的好方法。但是我不知道没有其他口头的方式可以做到这一点。

有没有一种方法可以使此操作更高效,更清洁?

1 个答案:

答案 0 :(得分:2)

您可以使用循环和%n在每个循环中扫描一个数字。 %n的目的是获取扫描使用的字符数。这样,您可以按数字迭代字符串编号。

这里是一个例子:

int main(int argc, char *argv[])
{
    char buf[20] = "1 2 3 4";  // Assume this is the data read using fgets
    int x;
    int offset = 0;
    int temp;
    while (sscanf(buf + offset, "%d%n", &x, &temp) == 1)
    {
        printf("At offset %d scanned %d\n", offset, x);
        offset += temp;
    }
}

输出:

At offset 0 scanned 1
At offset 1 scanned 2
At offset 3 scanned 3
At offset 5 scanned 4

添加一个在每个循环中递增的简单计数器将使您可以将数字存储在数组中。