这部分代码负责打开我的 data.txt 文件并从中读取几个数字(数组的大小和填充的数字),但虚拟编程实验室和 C 都说“找不到程序“”在可执行文件中”。我尝试用这种方法编写一个程序,该程序只会从 .txt 中读取 1 个数字,并且出现相同的错误,所以我想我这样做完全错误。还有其他方法可以读取 .txt 文件吗?谢谢
Array* input() {
int x,y;
int i;
Array *p;
FILE *f=fopen("data.txt", "r");
p = (Array*) malloc(sizeof(Array));
fscanf(f, "&d",&x);
fscanf(f, "&d",&y);
p->n1 = x;
p->n2 = y;
p->p1 = (int*) malloc(sizeof(int) * p->n1);
p->p2 = (int*) malloc(sizeof(int) * p->n2);
for(i=0; i < p->n1; i++)
fscanf(f, "%d", &p->p1[i]);
for(i=0; i < p->n2; i++)
fscanf(f, "%d", &p->p2[i]);
fclose(f);
return p;
}
最佳答案
以下建议代码:
- 可能会导致编译器输出:“untitled.c:114:9:警告:未使用的变量‘ptrToArray’[-Wunused-variable]”
- 执行所需的功能
- 正确检查 I/O 错误
- 在发生任何 I/O 错误后正确清理
- 为了灵 active ,将结构体的定义与该结构体的 typedef 分开
- 函数:
malloc()
需要一个size_t
类型的参数。这导致需要从int
到size_t
进行其他一些更改
- 为了便于阅读和理解:分隔代码块:
for
if
else
while
do ...while
switch
case
default
通过单个空行 - 为了可读性,在 C 运算符周围、括号内、逗号后、分号后、大括号内、方括号内插入空格
- 遵循公理:每行只有一个语句,并且每个语句(最多)一个变量声明。
- 正确地将函数
input()
的参数列表声明为void
- 为了可读性(人类)一致地缩进代码。每个左大括号“{”后缩进。每个右大括号“}”之前取消缩进。使用 4 个空格的缩进宽度。
- 为了便于阅读和理解:通过 2 个空行分隔函数。
- 将局部变量
i
的范围限制在其声明的代码块内,而不是函数的范围:input()
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
struct array
{
size_t n1;
size_t n2;
int *p1;
int *p2;
};
typedef struct array ARRAY;
ARRAY* input( void )
{
size_t x;
size_t y;
ARRAY *p;
FILE *f = fopen( "data.txt", "r" );
if( !f )
{
perror( "fopen for reading data.txt failed" );
exit( EXIT_FAILURE );
}
p = malloc( sizeof(ARRAY) );
if( !p )
{
perror( "malloc for an instance of struct array failed" );
fclose( f );
exit( EXIT_FAILURE );
}
if( fscanf( f, "%zu", &x ) != 1 )
{
fprintf( stderr, "fscanf for first data from file failed\n" );
fclose( f );
free( p->p1 );
free( p->p2 );
free( p );
exit( EXIT_FAILURE );
}
if( fscanf( f, "%zu", &y ) != 1 )
{
fprintf( stderr, "fscanf for second data from file failed\n" );
fclose( f );
free( p );
exit( EXIT_FAILURE );
}
p->n1 = x;
p->n2 = y;
p->p1 = malloc(sizeof(int) * p->n1);
if( !p->p1 )
{
perror( "malloc failed for pointer 'p1'" );
free( p );
fclose( f );
exit( EXIT_FAILURE );
}
p->p2 = malloc(sizeof(int) * p->n2);
if( !p->p2 )
{
perror( "malloc failed for pointer 'p2'" );
free( p->p1 );
free( p );
fclose( f );
exit( EXIT_FAILURE );
}
for( size_t i=0; i < p->n1; i++ )
{
if( fscanf(f, "%d", &p->p1[i]) != 1 )
{
fprintf( stderr, "fscanf for %zu value in array 'p1' failed\n", i );
fclose(f);
free( p->p1 );
free( p->p2 );
free( p );
exit( EXIT_FAILURE );
}
}
for( size_t i=0; i < p->n2; i++ )
{
if( fscanf(f, "%d", &p->p2[i]) != 1 )
{
fprintf( stderr, "fscanf for %zu value in array 'p2' failed\n", i );
fclose(f);
free( p->p1 );
free( p->p2 );
free( p );
exit( EXIT_FAILURE );
}
}
fclose(f);
return p;
}
int main( void )
{
ARRAY *ptrToArray = input();
free( ptrToArray->p1 );
free( ptrToArray->p2 );
free( ptrToArray );
return 0;
}
关于c - 这是打开 .txt 文件的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57852008/