gpt4 book ai didi

c - 在函数内读取文件,并且内容必须在使用 C 传递的参数中可用

转载 作者:行者123 更新时间:2023-11-30 17:15:52 25 4
gpt4 key购买 nike

我正在尝试读取函数内的文件,并希望在函数返回后将其内容传递给函数的参数中。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main()
{
char dest[10000];
copyString(dest);
printf("%s", dest);
}

copyString(outStr)
char *outStr;
{
char * buffer = 0;
long length;
FILE * f = fopen ("file.txt", "rb");

if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = (char *)malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
strcpy(outStr, buffer);
}

当我尝试上述操作时,它不会打印任何内容。我的代码有什么问题?请帮忙。我希望 dest 在 main 函数中包含文件的内容。

最佳答案

嗯,很好奇。

这对我有用。我有两个建议。

确保您的 file.txt 位于同一目录中。

您可以在 if (f) 条件中添加一个“else”子句,并在 else 中输入 perror("open")。

另外,让你的文件很小。 (从一开始就说一行)。您没有测试 strcpy 上的缓冲区溢出。您应该改用 strncpy。

关于c - 在函数内读取文件,并且内容必须在使用 C 传递的参数中可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838784/

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