gpt4 book ai didi

c - 如何将文本文件存储到 C 中的数组中

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

我正在尝试打开用户输入的文本文件并读取该文本文件,但一次打印该文本文件 60 个字符,所以我认为为了做到这一点,我需要将文本存储到一个数组中,并且如果一行超过 60 个字符,则应另起一行。但是,当我运行下面的代码时,会显示一条错误消息:C^@

#include <stdio.h>
#include <stdlib.h>


int main()
{
char arr[];
arr[count] = '\0';
char ch, file_name[25];
FILE *fp;

printf("Enter file name: \n");
gets(file_name);

fp = fopen(file_name,"r"); // reading the file

if( fp == NULL )
{
perror("This file does not exist\n"); //if file cannot be found print error message
exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name);

while( ( ch = fgetc(fp) ) != EOF ){
arr[count] = ch;
count++;
printf("%s", arr);}

fclose(fp);
return 0;
}

最佳答案

char arr[]; 无效。您需要指定大小。

array[count] = '\0';:count 未初始化。

gets(file_name); :gets 已被弃用且危险。请使用其他函数,如 scanf。

尝试以下代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int ch , count = 0;
char file_name[25];
FILE *fp;

printf("Enter file name: \n");
scanf(" %24s",file_name);

fp = fopen(file_name,"r"); // reading the file

if( fp == NULL )
{
perror("This file does not exist\n"); //if file cannot be found print error message
exit(EXIT_FAILURE);
}
fseek(fp, 0L, SEEK_END);
long sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);

char arr[sz];

while( ( ch = fgetc(fp) ) != EOF )
{
if( count < sz )
{
arr[count] = ch;
count++;
}
}
arr[sz] = '\0';
printf("The contents of %s file are :\n", file_name);
printf("arr : %s\n",arr);

fclose(fp);
return 0;
}

关于c - 如何将文本文件存储到 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593274/

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