[英]Random characters at the end of C read file
我一直在嘗試使用從這個答案中獲得的代碼讀取文件。
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
char * readfile(FILE * f)
{
char * buffer = 0;
long length;
if (f)
{
fseek(f, 0, SEEK_END);
length = ftell (f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length);
if (buffer) fread(buffer, 1, length, f);
fclose(f);
}
return buffer;
}
int main()
{
FILE * f = fopen("./file.txt", "r");
printf(readfile(f));
}
我的 function 確實返回文件的內容,但它也返回隨機字符。
contents╪▐>c☻ú
令人驚訝的是,每次我運行代碼時它們似乎都會發生變化。
contents╗╙ÿ▓.┤
我的文件的內容是“內容”。
我的問題是:如何修復我的代碼以使其不返回隨機字符?
C 中的字符串需要 null 終止。 當您讀取內容時,您的緩沖區字符串不會終止。 本質上,您正在根據需要打印文件內容,但讀取只是繼續在連續的 memory 中進行,直到偶然到達 null 字符。
我的 function 確實返回文件的內容,但它也返回隨機字符。
不。 function 只返回一個指針,而不是任何字符。
使用該指針的是printf()
調用,認為它是一個指向string的指針。 在 C 中,字符串始終包含最終'\0'
,否則它不是字符串。 它只是一個指向缺少null 字符的字符數組的指針,並導致未定義的行為,因為printf(s)
只知道從哪里開始(在s
處),但不知道在哪里結束。
更好的方法:返回一個指向字符串的指針。
最好也添加錯誤檢查。
// Let calling code close the file
char *readfile_alt(FILE * f) {
if (f == NULL || fseek(f, 0, SEEK_END) || (length = ftell(f)) == -1) {
return NULL;
}
char *buffer = length < SIZE_MAX ? malloc(length + 1LU) : NULL;
if (buffer == NULL || fread(buffer, 1, length, f) != length) {
free(buffer);
return NULL;
}
buffer[length] = '\0'; // Now buffer points to a string
return buffer;
}
此外, printf()
需要一個格式字符串。
最好使用printf("%s", readfile(f));
.
int main() {
FILE * f = fopen("./file.txt", "r");
if (f) {
char *s = readfile(f);
if (s) {
printf("%s\n", s);
free(s); // Free resource when done with them.
}
fclose(f); // Free resource when done with them.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.