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

时间:2018-03-14 14:24:36

标签: c

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

  • John Start 0
  • 使用*,15

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

  • John Start 0
  • 使用*,15
  • John Start 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:非常感谢。为了您的快速反应和有效的答案。至于大小* 10的东西,我想出了一个随机的想法,以处理其中一个Segmentation Fault错误。从未想过尺寸+ 1选项。我从你们身上学到了很多东西。很快就会出现一个新问题。再次感谢!

1 个答案:

答案 0 :(得分:1)

您的问题是您使用“text”作为字符串但未能执行此操作。 C中的“字符串”是以'\ 0'结尾的字符数组。

如果你使用任何字符串相关的功能,你必须不确定你给字符串! 所以在你分配了“text”(througth“temp”)之后,“text”还不是一个字符串,因为它不包含'\ 0'。 因为它在开头是一个“空”字符串,所以你必须通过

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

现在,为什么你的文件打印两次?不知道,但由于你的字符串未正确初始化,我必须在UB上下注。