获取一个文件并以C语言返回一个数组
您好,我必须创建一个函数,该函数以文件和指向整数的指针作为输入,并返回文件中的数字数组和指针的长度。我创建了这个程序,并在代码部分nuovoarray[I]=s中发现了问题,但我不知道如何解决它获取一个文件并以C语言返回一个数组,c,arrays,file,dynamic,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");
#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));
}
}
解决这个问题的方法不止一种。这里有一个 创建一个函数,该函数遍历文件并返回文件中存在的整数数 根据这个数字分配内存 创建第二个函数,其中整数从文件中读取并存储在分配的内存中
.阅读strcpy函数和返回语句。无意冒犯,你需要一本关于C的基础书。@SouravGhosh:strcpy?当然不是为了。。。文件中的数字数组。。。这就引出了几个相关的问题,例如他为什么要使用%s?@Jongware,这主要是针对=。正如我已经提到的,OP需要一个基本的C教程:你还没有发布你的实际代码,是吗?您只有一个指向整数的指针,并且不使用它执行任何操作。彻底地。
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;
}