无法读取c语言的文件。它创建一个新文件,而不是读取它
我已在目录中创建了一个文件,并希望将其读入。我使用以下代码打开并读取C语言的文件。但它会创建一个新文件,而不是读取旧文件无法读取c语言的文件。它创建一个新文件,而不是读取它,c,C,我已在目录中创建了一个文件,并希望将其读入。我使用以下代码打开并读取C语言的文件。但它会创建一个新文件,而不是读取旧文件 int main() { FILE * file; file = fopen ("file", "r+"); //file reading code fclose(file); return(0); } 如果您只想从文件中读取,则打开文件进行读取,即模式r(注意编号+): 如果您只想从文件中读取,则打开文件进行读取,即模式r(注意编号+): 您
int main()
{
FILE * file;
file = fopen ("file", "r+");
//file reading code
fclose(file);
return(0);
}
如果您只想从文件中读取,则打开文件进行读取,即模式
r
(注意编号+
):
如果您只想从文件中读取,则打开文件进行读取,即模式
r
(注意编号+
):
您正在使用'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或其他任何东西。e、 g
file = fopen ("File.txt", "r");
您正在使用'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或其他任何东西。e、 g
file = fopen ("File.txt", "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;
}
#包括
#包括
int main()
{
char ch,文件名[25];
文件*fp;
printf(“输入您希望查看的文件名\n”);
获取(文件名);
fp=fopen(文件名,“r”);//读取模式
如果(fp==NULL)
{
perror(“打开文件时出错。\n”);
退出(退出失败);
}
printf(“文件%s的内容是:\n”,文件名);
而((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
返回0;
}
我同意给出的答案,但您也可以另外检查文件是否存在。如下所示。如果程序无法识别该文件,它将通知您。避免使用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;
}
#包括
#包括
int main()
{
char ch,文件名[25];
文件*fp;
printf(“输入您希望查看的文件名\n”);
获取(文件名);
fp=fopen(文件名,“r”);//读取模式
如果(fp==NULL)
{
perror(“打开文件时出错。\n”);
退出(退出失败);
}
printf(“文件%s的内容是:\n”,文件名);
而((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
返回0;
}
check premissions to file check premissions to filefopen
本身不区分大小写或不区分大小写。这由底层操作系统/文件系统决定。IIRC,例如,带FAT的DOS不区分大小写,Linux具有vfat忽略大小写的装载选项。fopen
本身不区分大小写或不区分大小写。这由底层操作系统/文件系统决定。IIRC,例如,带FAT的DOS不区分大小写,Linux具有vfat忽略大小写的装载选项。请不要建议get
,尤其是对初学者。还有一个小提示:perror
末尾的换行符是奇数,传递的字符串后面是冒号(:
),空格和错误消息(以及换行符)。请不要建议获取
,尤其是对初学者。还有一个小提示:peror
末尾的换行符是奇数,传递的字符串后面是冒号(:
),空格和错误消息(以及换行符)。