c - 在 C 中获取一个文件并返回一个数组

标签 c arrays file dynamic

您好,我必须创建一个函数,该函数将文件和指向整数的指针作为输入,并返回文件内数字和指针长度的数组。我创建了这个程序,并在代码部分 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. 创建一个函数来遍历文件并返回文件中存在的整数数量。

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

关于c - 在 C 中获取一个文件并返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020070/

相关文章:

c++ - 使用 vbscript 部署 C++ 程序?

c - strcmp() unsigned char 到文件中的字符串

c - 是否有充分的理由编写我自己的 daemonize 函数而不是使用 daemon(3)?

PHP 数组...空括号的含义是什么?

javascript/jquery 有条件地用数组中的随机文本替换文本

arrays - 如何从 Angular2(Typescript) 中的 Json 数组中获取值的总和

android - 如何在 Android 上创建文本文件并将数据插入该文件

在没有锁的情况下检查 list_empty

c# - 拒绝访问任何文件夹,C#

c++ - 将多个文件中的信息添加到一个文件中 C++