我正在學習如何在 C 中撰寫和讀取檔案,并使用此代碼撰寫了文本
FILE *f = fopen("testingText.txt", "w");
char *text = "This is text1...";
fwrite(text, sizeof(char), strlen(text), f );
fclose(f);
當我閱讀此檔案的內容并使用此代碼列印時
FILE *f = fopen("testingText.txt", "r");
fseek(f, 0, SEEK_END);
unsigned int size = ftell(f);
fseek(f , 0, SEEK_SET);
char *content = (char *)malloc(size);
fread(content, sizeof(char), size, f);
printf("File content is...\n%s", content);
free(content);
fclose(f);
它給出了這樣奇怪的結果
檔案內容是... 這是 text1...Path=C:* ┬#?╩eò *
當我再次運行代碼時,它會給出不同的奇怪的東西。
uj5u.com熱心網友回復:
檔案中沒有空終止符,因此您需要在列印從檔案中讀取的內容之前手動添加它。
例子:
char *content = (char *)malloc(size 1); // 1 for the null terminator
size_t chars_read = fread(content, 1, size, f); // store the returned value
content[chars_read] = '\0'; // add null terminator
printf("File content is...\n%s\n", content); // now ok to print
uj5u.com熱心網友回復:
以下行是錯誤的:
printf("File content is...\n%s", content);
printf與%s轉換格式說明符一起使用需要一個以 null 結尾的字串。但是,您的字串不是以空值結尾的。
為了列印非空終止的字符序列,您可以撰寫以下代碼:
printf( "File content is...\n%.*s", (int)size, content );
或者您可以手動添加終止空字符,使用以下行:
content[size] = '\0';
但是,這將超出范圍寫入記憶體緩沖區content,因為您沒有為空終止字符分配任何空間。malloc因此,您應該在函式呼叫中分配一個額外的位元組。
另一個問題是 usingftell不是確定檔案長度的可靠方法。ISO C 標準不保證這會起作用。
例如,在 Microsoft Windows 上,這將為您提供二進制模式下的檔案長度(即使檔案以文本模式打開)。但是,文本模式下檔案的長度是不同的,因為在 Microsoft Windows 上\r\n會轉換為行尾。\n
因此,如果您想讀取長度未知的文本檔案的內容,最好在回圈中一次讀取一行,使用以下函式fgets:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char line[100];
//attempt to open file
fp = fopen( "testingText.txt", "r" );
//verify that file is open
if ( fp == NULL )
{
fprintf( stderr, "error opening file!\n" );
exit( EXIT_FAILURE );
}
printf( "File content is...\n" );
//print one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
//the following code will work even if "fgets" only
//reads a partial line, due to the input buffer not
//being large enough
//print the line to standard output
fputs( line, stdout );
}
//cleanup
fclose( fp );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416826.html
標籤:
下一篇:在檔案夾內迭代并僅復制子檔案夾
