2020-12-11 C++文件操作

本文介绍了使用C++进行文件操作的基本方法,包括如何判断文件是否存在、创建文件、读取文件内容及向文件写入数据等核心步骤。特别注意使用ios::out和ios::trunc模式打开文件时可能引起的数据丢失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 判断文件是否存在

#include<io.h>

int _access(const char *pathname, int mode);//mode设置为0 表示仅检查文件是否存在

if(_access(path, 0) == 0)
{
    cout<<"文件存在"<<endl;
}

返回0表示文件存在

2. 新建文件

#include <fstream>

void create_newfile_c(const char *path)
{
    FILE *ff = fopen(path, "w"); 
    if (ff) fclose(ff);
}

void create_newfile_cpp(const char *path)
{
    fstream ff(path, ios::trunc | ios::out);
    ff.close();
}

void create_newfile_if_not_exists(const char *path)
{
    if(_access(path, 0) != 0)    //如果文件不存在
        create_newfile_cpp(path);
}

3. 读文件

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

string read_first_word_of_txt(const char* path)
{
    string str;
	fstream f1(path, ios::in);
	
    f1>>str;    //读到第一个空格或换行为止
	f1.close();

    return str;
}

string read_first_line_of_txt(const char* path)
{
    string str;
	fstream f1(path, ios::in);
	
	getline(f1, str);    //读到换行为止, 也就是读一整行
	f1.close();

    return str;
}

int main()
{
    cout<< read_first_word_of_txt("./test.txt") <<endl;
    cout<< read_first_line_of_txt("./test.txt") <<endl;
    
    system("pause");
    
    return 0;
}

test. text 

001 this is a test
002 this is a test

输出:

001
001 this is a test

4. 写文件

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

void append_new_line_to_txtfile(const char* path, const char* newline)
{
    //fstream f1(path, ios::out);             //原文件会先被清空再写入
	//fstream f1(path, ios::out|ios::trunc);  //原文件会先被清空再写入
    //fstream f1(path, ios::app);             //在原文件后追加
    
	fstream f1(path, ios::out|ios::app);      //在原文件后追加
	
    f1<< newline <<endl;
    
	f1.close();
}

int main()
{
    append_new_line_to_txtfile("./test.txt", "this is a new line ");
    
    return 0;
}

用ios::out和ios::trunc方式打开文件时,原文件会先被清空再写入,要小心数据丢失。

5. 获取文件大小

SEEK_SET:基准位置为文件开头,即offset表示距离文件开头的偏移量。
SEEK_CUR:基准位置为文件当前位置,即offset表示距离文件当前位置的偏移量。
SEEK_END:基准位置为文件末尾

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

long get_file_size(const char* path)
{
    FILE* f = fopen(path, "rb");
    if(f == NULL)
    {
        printf("Failed to open file\n");
        return 0;
    }
    
    fseek(f, 0, SEEK_END);
    long filesize = ftell(f);
    fseek(f, 0, SEEK_SET);
    
    return filesize;
}


int main()
{
    printf("filesize  %d Bytes\n", get_file_size("./test.txt"));
    
    system("pause");
    
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KeepLearning_wj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值