C language preliminary classic question 16 --- copy the content of one file to another file

//将fp1所指向的文件的内容复制到fp2所指向的文件里面
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp1,*fp2 ;
    char c;
    if ((fp1=fopen("I:\\cstudy\\project1\\1.txt", "r"))==NULL)//字符串中两个\\相当于一个\
    {
        printf("connot open\n");
        exit(0);//当文件打开失败时,立即退出。原因:后面的代码对文件进行操作会出现错误。
    }
    if ((fp2=fopen("I:\\cstudy\\project1\\2.txt", "w"))==NULL)
    {
        printf("connot open\n");
        exit(0);
    }

    while ((c = fgetc(fp1)) != EOF)//当读取的字符不是文件的结束符
    {
        fputc(c,fp2);
    }
    fclose(fp1);
    fclose(fp2);
    return 0;
}

Use the software: Code::Blocks
to run the results:
write picture description here


fopen various opening methods:

r Opens the file as read-only, allowing only reading, not writing. The file must exist.
r+ opens the file for read/write, allowing both reading and writing. The file must exist.
rb+ opens a binary file for read/write, allowing data to be read/written.
rt+ opens a text file for read/write, allowing both reading and writing.
w Open the file in write-only mode. If the file exists, the length is cleared to 0, that is, the content of the file disappears. If it does not exist, the file is created.
w+ opens the file in read/write mode. If the file exists, the length of the file will be cleared to zero, that is, the content of the file will disappear. Create the file if it does not exist.
a Opens a write-only file for appending. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be preserved (EOF is reserved).
a+ Opens a file for read/write for appending. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be preserved (the original EOF character is not preserved).
wb opens or creates a new binary file in write-only mode, allowing only data to be written.
wb+ opens or creates a binary file in read/write mode, allowing both reading and writing.
wt+ opens or creates a text file in read/write mode, allowing reading and writing.
at+ opens a text file for read/write, allowing reading or appending data to the end of the text.
ab+ opens a binary file for read/write, allowing reading or appending data at the end of the file.


A little tip about quickly copying file paths:

  1. open cmd
  2. Drag a file into cmd, the path of the file is displayed on cmd
  3. Right-click to complete the copy

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326293402&siteId=291194637