繁体   English   中英

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

[英]How do I store a text file into an array in C

我正在尝试打开用户输入的文本文件并读取此文本文件,但一次打印 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;
}

fgetc总是读取下一个字符,直到EOF 使用fgets()代替:

char *fgets(char *s, int size, FILE *stream)

fgets() reads in at most one less than size characters from stream and 
stores them into the buffer pointed to by s. Reading stops after an EOF 
or a newline. If a newline is read, it is stored into the buffer. A 
terminating null byte (aq\0aq) is stored after the last character in the 
buffer. 

三个问题:

  1. 变量count没有初始化,所以它的值是不确定的,使用它会导致未定义的行为

  2. 调用printf(arr)arr视为字符串,但arr未终止,这再次导致未定义行为

  3. count的增量在循环之外

要解决前两个问题,您必须首先将count初始化为零,然后必须在循环后终止字符串:

arr[count] = '\0';

但是,你的printf(arr)调用还是很有问题的,如果用户输入了一些printf格式的代码,那会怎么样呢? 这就是为什么你永远不应该用用户提供的输入字符串调用printf ,而只是简单地做

printf("%s", arr);

如果您读取的文件内容超过 59 个字符,那么您也会遇到一个非常大的问题,然后您将溢出数组。

1)你的while循环没有正确分隔。 在没有{ }块的情况下,指令arr[count] = ch; 是唯一重复的。

我想它也应该包括count的增加

while( ( ch = fgetc(fp) ) != EOF )
  {
     arr[count] = ch;
     count++;
     ....
  }

除其他外(测试计数器等)。

2)没有必要读取和存储在数组中。 完全可以在读取每个字符时立即传输,并在需要时添加换行符(新行,超过 60 个限制)。

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

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM