C在打开文件时编程fopen()

new*_*bie 1 c fopen

我一直在想这个.我读过的大多数书都表明,当你打开一个文件而你发现文件不存在时,你应该输入一个没有这样文件的错误然后退出系统...

FILE *stream = NULL; 
stream = fopen("student.txt", "rt");
if (stream==NULL) {
    printf(“Cannot open input file\n”);
    exit(1);
else {printf("\nReading the student list directory. Wait a moment please...");
Run Code Online (Sandbox Code Playgroud)

但我认为这不是那样做的.当你发现你正在打开的文件不存在时,为什么不自动创建一个新的呢?即使您在使用该程序时不会在文件上写入(但下次将使用它).我不确定这是否有效.我刚刚来到这里并且没有任何编程经验,所以我问你的意见在尝试打开文件时创建文件的优点和缺点是什么,而不是像通常在书上一样退出系统.

FILE *stream = NULL; 
stream = fopen("student.txt", "rt");
     if (stream == NULL) stream = fopen("student.txt", "wt");
     else {
          printf("\nReading the student list directory. Wait a moment please...");
Run Code Online (Sandbox Code Playgroud)

您的意见将受到高度赞赏.谢谢.

And*_*ong 8

因为从你的例子来看,它似乎是一个输入文件,如果它不存在,没有点创建它.

例如,如果该程序应该打开一个文件,然后计算其中有多少个元音,那么如果它不存在,我就没有太多意义来创建该文件.

我的价值0.02美元.


Hua*_*Lei 5

参数模式:

 ``r''   Open text file for reading. 
 ``r+''  Open for reading and writing. 
 ``w''   Truncate file to zero length or create text file for writing.
 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  
 ``a''   Open for writing.  The file is created if it does not exist.
 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  
Run Code Online (Sandbox Code Playgroud)

你的问题很简单.阅读上面的描述,当你调用fopen()时,你应该决定使用哪种模式.请考虑为什么"r"和"R +"不创建一个文件,为什么一个文件被截断的"w"和"W +",等等.所有这些都是合理的设计.