📜  文件打开模式(r与r +)

📅  最后修改于: 2021-05-28 02:05:22             🧑  作者: Mango

开始读写操作之前,必须先打开文件。打开文件会在操作系统和文件函数之间建立链接。

打开文件的语法:

FILE *fp;
  fp = fopen( " filename with extension ", " mode " );

详细打开文件:
FILE :在stdio.h头文件中定义的结构。 FILE结构为我们提供了有关FILE的必要信息。
fp :包含结构FILE地址的文件指针。
fopen() :此函数将在指定的“模式”下打开名称为“ filename”的文件。

不同的阅读模式:

  1. [R
  2. r +
  3. 对于二进制文件:rb,rb +,r + b

区别:

r mode r+ mode
Purpose Opens an existing text file for reading purpose. Opens a text file for both reading and writing.
fopen Returns if FILE doesn’t exists NULL Create New File
fopen returns if FILE exist Returns a pointer to the FILE object. New data is written at the start of existing data
file pointer position at the first char of the file at the first char of the file

用于在r模式下打开文件的C程序:

#include 
  
void main()
{
    FILE* fp;
    char ch;
    // Open file in Read mode
    fp = fopen("INPUT.txt", "r+");
  
    // data in file: geeksforgeeks
  
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fclose(fp); // Close File after Reading
}

输出:

geeksforgeeks

注意:打开的文件在处理后应在程序中关闭。

用于在r +模式下打开文件的C程序:

#include 
  
void main()
{
    FILE* fp;
    char ch;
    // Open file in Read mode
    fp = fopen("INPUT.txt", "r+");
  
    // content of the file:geeksforgeeks
  
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fprintf(fp, " online reference.");
  
    fclose(fp); // Close File after Reading
  
    // content of the file: geeksforgeeks online reference.
  
    fp = fopen("INPUT.txt", "r+"); // Open file in r + mode
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fclose(fp);
}

输出:

geeksforgeeks online reference

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。