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;
}