我有一个文件,我需要读入缓冲区(char *),但问题是该文件在有效文本之间有一些“有趣的字符”。
所以当我写下如下代码时:
FILE *fp;
if((fp = fopen(".\\test.txt", "rt"))==NULL){
printf("Cannot open file2\n");
}
fseek(fp, 0, SEEK_END);
long int fsize = ftell(fp);
rewind(fp);
//char *buffer2 = malloc(fsize * sizeof(char));
buffer = malloc(fsize * sizeof(char));
fread(buffer, 1, fsize, fp);
buffer[fsize] = '\0';
fclose(fp);
printf("fsize = %i\n", fsize);
printf("Buffer = %s\n", buffer);
它只打印出文本文件的第一部分,如下所示:
缓冲区=标题
显然在第一个NUL char停止了。
是否可以通过任何方式读取文件的整个缓冲区,包括有趣的字符?
或者这在C中是不可能的吗?
正确读取FSIZE,只是FREAD不读取整个缓冲区; - (
非常感谢任何帮助; - )
由于
林顿
更新:好的,我有点傻.....如果我把缓冲区写入一个文件,它包含了所有内容,只有当我把它写到屏幕上它才会停止在null,这样就是细
答案 0 :(得分:1)
不要以“文本”模式(“rt”)打开文件,而是使用二进制模式(“rb”)。
此外,它可能正在读取数据,但printf("Buffer = %s\n", buffer)
只会打印到第一个NUL,因此您的调试不会按照您的意愿执行。您可能想要编写一个小的十六进制转储函数。
答案 1 :(得分:0)
如何读取文件的所有内容,包括有效文本之间的 NUL 字符?
错误:
如果尝试创建一个字符串,请分配足够的空间。 OP 的代码是 1 短。如果读取的数据可能包含空字符,这是一个可疑的目标。
以二进制模式打开 @Lawrence Dol
更多的错误检查很有用。
// FILE *fp = fopen(".\\test.txt", "rt");
FILE *fp = fopen(".\\test.txt", "rb");
if (fp==NULL) {
printf("Cannot open file2\n");
exit(-1);
}
if (fseek(fp, 0, SEEK_END)) {
printf("fseek() trouble\n");
exit(-1);
}
long fsize = ftell(fp);
if (fsize == -1 || fsize >= SIZE_MAX) {
printf("fell() trouble\n");
exit(-1);
}
// Add 1 if trying to make a string.
size_t sz = (size_t) fsize;
if (making_a_string) sz++;
rewind(fp);
char *buffer = malloc(sizeof *buffer * sz);
if (buffer == NULL && sz > 0) { // Tolerate a file size of 0
printf("malloc() trouble\n");
exit(-1);
}
size_t in = fread(buffer, 1, fsize, fp);
fclose(fp);
if (in != fsize) {
printf("fread() trouble\n");
exit(-1);
}
if (making_a_string) {
buffer[fsize] = '\0';
}
要打印整个数据,请使用 fwrite()
。为了打印字符数组,不需要像字符串那样尾随空字符,而是使用字符数组的长度。
printf("fsize = %ld\n", fsize); // Note: %ld
printf("Buffer = <", );
fwrite(buffer, 1, fsize, stdout);
printf(">\n");