gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:49:57 26 4
gpt4 key购买 nike

通过以下程序,我希望读取一个文件(例如文本文件)并将其所有内容存储在变量中。因此,为了实现这一目标,我在 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/

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