简体   繁体   English

无法使用C语言读取文件。 它创建一个新文件,而不是读取它

[英]unable to read a file in c language. it creates a new file instead of reading it

I have creates a file in directory and want to read it in. I am using the following code to open and read a file in C-Language. 我已经在目录中创建了一个文件,并希望读入。我正在使用以下代码在C语言中打开和读取文件。 But it creates a new file instead of reading the old file. 但是它会创建一个新文件,而不是读取旧文件。

int main()
{
   FILE * file;
   file = fopen ("file", "r+");
   //file reading code
   fclose(file);
   return(0);
}

you are using 'r+' mode to open the file. 您正在使用“ r +”模式打开文件。 It creates a new file if not already exist in the directory. 如果目录中尚不存在该文件,它将创建一个新文件。 see the following code for your help. 请参阅以下代码以获取帮助。

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);
}

also check the file name that you are using in fopen() function.It is case sensitive and also check the extension of that file eg; 还要检查您在fopen()函数中使用的文件名。它区分大小写,并检查该文件的扩展名。 .txt or .data or what ever. .txt或.data或其他内容。 eg; 例如;

file = fopen ("File.txt", "r");

如果您只打算从文件中读取文件,则将其打开以进行读取,即模式r (注意no + ):

file = fopen ("file", "r");

I agree with answers given but you can also additionally check if file is present or not. 我同意给出的答案,但您也可以另外检查文件是否存在。 Something as below. 如下所示。 In case program does not recognize the file it will let you know. 如果程序无法识别该文件,它将通知您。 Avoid using r+ in case you want to read an already existing file. 如果要读取已经存在的文件,请避免使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM