[英]unable to read a file in c language. it creates a new file instead of reading it
我已經在目錄中創建了一個文件,並希望讀入。我正在使用以下代碼在C語言中打開和讀取文件。 但是它會創建一個新文件,而不是讀取舊文件。
int main()
{
FILE * file;
file = fopen ("file", "r+");
//file reading code
fclose(file);
return(0);
}
您正在使用“ r +”模式打開文件。 如果目錄中尚不存在該文件,它將創建一個新文件。 請參閱以下代碼以獲取幫助。
int main()
{
FILE * file;
file = fopen ("file", "r");
if(file !== NULL)
// to do file reading code
else
printf("error in reading file");
fclose(file);
return(0);
}
還要檢查您在fopen()函數中使用的文件名。它區分大小寫,並檢查該文件的擴展名。 .txt或.data或其他內容。 例如;
file = fopen ("File.txt", "r");
如果您只打算從文件中讀取文件,則將其打開以進行讀取,即模式r
(注意no +
):
file = fopen ("file", "r");
我同意給出的答案,但您也可以另外檢查文件是否存在。 如下所示。 如果程序無法識別該文件,它將通知您。 如果要讀取已經存在的文件,請避免使用r +。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.