在 C 中取一个文件和 return 一个数组

Take a file and return an array in C

你好,我必须创建一个函数,它将一个文件和一个指向整数的指针以及 returns 文件中的数字数组和指针的长度作为输入。我创建了这个程序并在代码部分发现了问题 nuovoarray[i] = s 但我不知道如何解决它。

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

int* leggiArray(char* nomefile, int* n){
  FILE* file = fopen(nomefile,"r");
  char* nuovoarray = (char*) malloc(sizeof(char));
  int i=0;
  char s[256];
  while(fscanf(file,"%s",s)!=EOF){
    nuovoarray[i] = s;
    i++;
    nuovoarray = realloc(nuovoarray,i*sizeof(char));
  }
}

解决问题的方法不止一种。这是一个。

  1. 创建一个遍历文件的函数,returns 文件中存在的整数个数。

  2. 根据该数字分配内存。

  3. 创建第二个函数,其中从文件中读取整数并将其存储在分配的内存中。

int getNumberOfIntegers(char const* file)
{
   int n = 0;
   int number;
   FILE* fptr = fopen(file, "r");
   if ( fptr == NULL )
   {
      return n;
   }

   while ( fscanf(fptr, "%d", &number) == 1 )
   {
      ++n;
   }

   fclose(fptr);
   return n;
}

int readIntegers(char const* file, int* numbers, int n)
{
   int i = 0;
   int number;
   FILE* fptr = fopen(file, "r");
   if ( fptr == NULL )
   {
      return i;
   }

   for ( i = 0; i < n; ++i )
   {
      if ( fscanf(fptr, "%d", &numbers[i]) != 1 )
      {
         return i;
      }
   }

   return i;
}

int main()
{
   int n1;
   int n2;
   int* numbers = NULL;
   char const* file = <some file>;

   // Get the number of integers in the file.
   n1 = getNumberOfIntegers(file);

   // Allocate memory for the integers.
   numbers = malloc(n1*sizeof(int));
   if ( numbers == NULL )
   {
      // Deal with malloc problem.
      exit(1);
   }

   // Read the integers.
   n2 = readIntegers(file, numbers, n1);
   if ( n1 != n2 )
   {
      // Deal with the problem.
   }

   // Use the numbers
   // ...
   // ...

   // Deallocate memory.
   free(numbers);

   return 0;
}