gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:09:53 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com