如何在C中将文本文件复制到字符串? [英] How to copy text file to string in C?
问题描述
我需要将文本文件的内容复制到动态分配的字符数组.
I need to copy the contents of a text file to a dynamically-allocated character array.
我的问题是获取文件内容的大小;Google透露我需要使用 fseek
和 ftell
,但是显然,该文件需要以二进制模式打开,并且只会产生垃圾.
My problem is getting the size of the contents of the file; Google reveals that I need to use fseek
and ftell
, but for that the file apparently needs to be opened in binary mode, and that gives only garbage.
我尝试以文本模式打开,但是我得到了奇怪的数字.这是代码(为了清楚起见,我省略了简单的错误检查):
I tried opening in text mode, but I get weird numbers. Here's the code (I've omitted simple error checking for clarity):
long f_size;
char* code;
size_t code_s, result;
FILE* fp = fopen(argv[0], "r");
fseek(fp, 0, SEEK_END);
f_size = ftell(fp); /* This returns 29696, but file is 85 bytes */
fseek(fp, 0, SEEK_SET);
code_s = sizeof(char) * f_size;
code = malloc(code_s);
result = fread(code, 1, f_size, fp); /* This returns 1045, it should be the same as f_size */
推荐答案
问题的根源在这里:
FILE* fp = fopen(argv[0], "r");
argv [0]是您的可执行程序,而不是参数.它当然不会是文本文件.尝试argv [1],然后看看会发生什么.
argv[0] is your executable program, NOT the parameter. It certainly won't be a text file. Try argv[1], and see what happens then.
这篇关于如何在C中将文本文件复制到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!