C++文件的读取与写入

2023-08-27  本文已影响0人  红鲤鱼与绿鲤鱼与驴与鱼

一、读取操作

/**
 文件读取操作
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main(){
    //文件路径
    char* filename ="/Users/aaa/Documents/C++File/test.txt";

    FILE* file = fopen(filename, "rw");
    if (!file) {
        printf("文件不存在\n");
        exit(0);
    }
    
    char buff[1024];
    //读取文件
    while (fgets(buff, 1024, file)) {
        printf("文件内容:%s\n",buff);
    }
  //关闭流/文件
    fclose(file);
    return 0;
}

fopen 方法

打开文件,参数1(文件路径、文件源); 参数2(打开的模式,r:读w:写rb:作为二进制文件读取wb:作为二进制文件写入)

fgets 方法

读取文件的内容,将内容读取到缓存区(这里指buff变量)
参数1:缓存区域
参数2:缓存区的长度
参数3:文件的指针变量

fclose 方法

关闭文件

二、写入操作

/**
 文件的写入
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main(){
    char * fileName = "/Users/aaa/Documents/C++File/test2.txt";
    //打开文件,当模式为"w“会自动创建文件
    FILE* file = fopen(fileName, "w");
    if (!file) {
        printf("打开文件失败...\n");
        exit(0);
    }
    
    char* content = "这是需要写入的内容";
    //写入
    fputs(content, file);
    //关闭文件
    fclose(file);
    return 0 ;
}

fopen 方法第二个参数为 w 或者 wb 时表示写入文件,如果文件不存在会创建文件

fputs 方法

将内容写入文件
参数1:需要写入的内容
参数2:文件指针变量

上一篇 下一篇

猜你喜欢

热点阅读