c - 从文件中读取为 char 数组

标签 c file arrays char

我正在读取一个文件,当我读取时,它会逐行读取并打印出来

我真正想要的是我想要一个包含文件中所有字符的字符数组并打印一次,

这是我的代码

if(strcmp(str[0],"@")==0)
        {
            FILE *filecomand;
            //char fname[40];
            char line[100];
            int lcount;
            ///* Read in the filename */
            //printf("Enter the name of a ascii file: ");
            //fgets(History.txt, sizeof(fname), stdin);

            /* Open the file.  If NULL is returned there was an error */
            if((filecomand = fopen(str[1], "r")) == NULL) 
            {
                    printf("Error Opening File.\n");
                    //exit(1);
            }
            lcount=0;
            int i=0;
            while( fgets(line, sizeof(line), filecomand) != NULL ) {
                /* Get each line from the infile */
                    //lcount++;
                    /* print the line number and data */
                    //printf("%s", line);  

            }

            fclose(filecomand);  /* Close the file */

最佳答案

您需要确定文件的大小。一旦你有了它,你就可以分配一个足够大的数组并一次性读取它。

有两种方法可以确定文件的大小。

使用fstat:

struct stat stbuffer;
if (fstat(fileno(filecommand), &stbuffer) != -1)
{
    // file size is in stbuffer.st_size;
}

使用 fseekftell:

if (fseek(fp, 0, SEEK_END) == 0)
{
    long size = ftell(fp)
    if (size != -1)
    {
        // succesfully got size
    }

    // Go back to start of file
    fseek(fp, 0, SEEK_SET);
}

关于c - 从文件中读取为 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2975931/

相关文章:

c - C 程序正确启动但 printf 不显示任何内容

Java7 WatchService - 尝试删除递归监视的嵌套目录时出现拒绝访问错误(仅限 Windows)

Python - 对数组进行排序以在其中进行搜索的最有效方法

python - 数组 Python 的复杂子集和合并

c - 从文件中的行读取最大单词时重复标记?

arrays - 环回更新对象的属性数组

c - 从配置文件定义数据结构

c - 如何从 XC16 上的自定义部分删除不需要的数据填充

如果我输入一个等于 INT_Max+1 的数字,计算机不会返回 -1

Java:将数组写入文本文件