gpt4 book ai didi

c - 我如何从文本文件输入文本(c)

转载 作者:行者123 更新时间:2023-11-30 16:32:51 25 4
gpt4 key购买 nike

如何使用 fgets 从文本文件中输入文本,同时使用 2D 数组进行输入?

main(){

char text[1000][1000];
FILE *fptr;
char fname[100];
printf("input file name:");
scanf("%s",fname);
fptr=fopen(fname,"w");
if(fptr==NULL){
printf("Error in opening file");
exit(1);
}
else{
}
}

最佳答案

以下建议代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确检查错误
  4. 退出前适当清理
  5. 记录哪个头文件公开了哪些函数以及哪些#define

现在建议的代码:

#include <stdio.h>    // FILE, printf(), scanf(), fprintf()
// fopen(), fclose(), stderr, fflush()
#include <stdlib.h> // exit(), EXIT_FAILURE, realloc()
#include <string.h> // strdup()

#define MAX_FILENAME_LEN 99
#define MAX_LINE_LEN 1000

int main( void )
{
FILE *fptr;
char filename[ MAX_FILENAME_LEN +1 ];

printf("input file name:");
fflush( stdout );
if( scanf( "%99s", filename ) != 1 )
{
fprintf( stderr, "scanf failed to read the file name\n" );
exit( EXIT_FAILURE );
}

// implied else, scanf successful

fptr = fopen( filename, "w" );
if( !fptr )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}

// implied else, fopen successful

char **savedText = NULL;
size_t numLines = 0;
char line[ MAX_LINE_LEN ];

while( fgets( line, sizeof(line), fptr ) )
{
char *temp = realloc( savedText, (numLines+1)*sizeof(char*) );
if( !temp )
{
perror( "realloc failed" );
fclose( fptr );
for( size_t i=0; i<numLines; i++ )
{
free( savedText+i );
}
free( savedText );
exit( EXIT_FAILURE );
}

// implied else, realloc successful

*savedText = temp;
savedText[ numLines ] = strdup( line );
if( !savedText+numLines )
{
perror( "strdup failed" );
fclose( fptr );
for( size_t i=0; i<numLines; i++ )
{
free( savedText+i );
}
free( savedText );
exit( EXIT_FAILURE );
}

// implied else, strdup successful

numLines++;

} // end while()

fclose( fptr );
for( size_t i=0; i<numLines; i++ )
{
free( savedText[ i ] );
}
free( savedText );
return 0;
}

关于c - 我如何从文本文件输入文本(c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49960743/

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