C 文件指针两次返回文件内容

标签 c

通过以下程序,我希望读取一个文件(例如文本文件)并将其所有内容存储在变量中。因此,为了实现这一目标,我在 Stack Overflow 建议的帮助下编写了以下内容。但是,该程序会两次返回文件的内容。 例如,让以下程序读取包含以下内容的文本文件:

  • 约翰开始 0
  • 使用 *,15

然后,程序将显示以下内容:

  • 约翰开始 0
  • 使用 *,15
  • 约翰开始 0
  • 使用 *,15

因此,我希望您能帮忙找出问题所在。预先非常感谢!

    //Program to read a file and store it's contents in a single variable
    #include<stdio.h>
    #include<ctype.h>
    #include<string.h>
    #include<stdlib.h>

    /*Reads contents of a file and returns address of variable, in which file contents are stored*/
    char* fileRead(char*);
    //Concatenates 2 strings
    char* concat(char*,char*);  
    //Calculates the size of the file
    unsigned long fsize(char* file);

    int main()
    {

      char *prt, *out;
      //Allocate memory & take the input of the file name to read
      prt = malloc(256);
      printf("\nEnter the name of the file : \t");
      scanf("%255s",prt);
      //Copy the address of read data & output it
      out = fileRead(prt);
      printf("\nContents : \n-----------------\n%s", out);

      free(out);    
      free(prt);
      return 0;
    }

    char* fileRead(char *file)
    {   
      //function to read the contents of a file

      FILE  *fip;
      char *text, *temp, read[1024];
      int size, i=0;

      fip=fopen(file, "r");
      size=(int)fsize(file);

      temp = malloc(size*10);
      text = temp;
      //If the file doesn't exist then...
      if(fip==NULL)
      {
        temp = strdup("ERROR : File doesn't exist! Please try again!\n");
        return temp;
      } 
      //Begin concatenation, once after the file reading has been initiated
      while(fgets(read, 1024, fip) != NULL)
      {
        temp = concat(text,read);i++;
      }

      fclose(fip);

      return text;
     }

     char* concat(char* dest, char* src)
     {  
      //function to concatenate src to dest
      while(*dest) dest++;  
      while(*dest++ = *src++);
      return --dest;
     }

     unsigned long fsize(char* file)
     {  
      //calculates the size of file
      FILE * f = fopen(file, "r");
      fseek(f, 0, SEEK_END);
      unsigned long len = (unsigned long)ftell(f);
      fclose(f);
      return len;
     }

编辑1:非常感谢大家。为您提供快速响应和高效解答。至于 size*10 的事情,这是我想出的一个随机想法,用于处理其中一个段错误错误。从来没想过尺寸+1 选项。我从你们身上学到了很多东西。很快就会提出新问题。再次感谢!

最佳答案

您的问题是您使用“text”作为字符串但未能做到这一点。 C 中的“字符串”是一个以“\0”结尾的字符数组。

如果您使用任何与字符串相关的函数,您必须不确定您是否给出了字符串! 因此,在分配“text”(通过“temp”)后,“text”还不是字符串,因为它不包含“\0”。 由于它的开头是一个“空”字符串,因此您必须通过执行

进行初始化
text[0] = '\0';

现在,为什么您的文件被打印两次?不知道,但我必须打赌 UB,因为你的字符串没有正确初始化。

关于C 文件指针两次返回文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280221/

相关文章:

c - 如何在循环中将普通 char 数组中的元素分配给 const char * 数组?

无法将字符串从 Ruby 传递到我的 Rust 函数中

c - 除了返回值之外,在 C 中变量的地址是否必须发送到函数才能修改其值?

c - 来自 printf() 的随机段错误,有人可以帮忙解释一下吗?

c++ - PIC代码无法编译

c - 为什么这个C程序会无限循环?

c - 为什么我的二分搜索只能按此顺序处理 if 语句?

c - 用户输入字符评估为常数字符

sql - 最简单的标准 C 语言 SQL 实现,可用于基于 Linux 的 ARM 终端

c - C 中的 tcp 客户端/服务器中带有线程的字符串