这个系列是 Linux 下的 C++ 编程教程
在Linux下,通过C++读写文件,分为
C++方式
和Linux方式
,本教程使用的是C++方式
。
判断文件是否存在
可以使用 ifstream 来判断文件是否存在
bool check_file_test(char const *filePath)
{
// 用 ifstream 来判断文件是否存在
ifstream testFile(filePath);
if(!testFile)
{
cout << "file not exit" << endl;
return false;
}
else
{
cout << "file exit" << endl;
return true;
}
return false;
}
int main(int argc, char** argv)
{
char fileName[] = "./test_file.txt";
check_file_test(fileName);
return 0;
}
这个程序将判断在执行目录下,是否存在文件./test_file.txt
。
创建新文件
添加以下函数新建文件
void generate_file_test(char const *fileName)
{
ofstream out;
out.open(fileName);
// 判断文件是否已经打开
if(out.is_open())
{
cout << "file created succeed" << endl;
out.close();
return true;
}
else
{
cout << "file created failed" << endl;
out.close();
return false;
}
out.close();
return false;
}
修改main函数:
int main(int argc, char** argv)
{
char fileName[] = "./test_file.txt";
if(!check_file_test(fileName))
{
generate_file_test(fileName);
}
return 0;
}
** 这里留一个问题,如果fileName中,需要创建的文件是在一个不存在的目录例如
"/not_exit_dict/test_file.txt"
,这时创建文件会失败。新手暂时未找到好的解决方法。
向文件写入内容
添加一下写文件函数:
bool write_into_file(char const *fileName, char const *content)
{
ofstream out;
out.open(fileName);
if(!out.is_open())
{
cout << "file not exit" << endl;
return false;
}
else
{
out << content;
cout << "write succeed" << endl;
out.close();
return true;
}
return false;
}
修改main函数内容:
int main(int argc, char** argv)
{
char fileName[] = "./test_file.txt";
char content[] = "Hello, file.";
if(!check_file_test(fileName))
{
generate_file_test(fileName);
}
write_into_file(fileName, content);
return 0;
}
读取文件内容
添加读取文件函数:
string read_from_file(char const *fileName)
{
char content[256];
string line;
ifstream in;
in.open(fileName);
if(!in.is_open())
{
cout << "file not exit" << endl;
}
else
{
in.getline(content,256);
line = content;
}
return line;
}
修改main函数
int main(int argc, char** argv)
{
char fileName[] = "./test_file.txt";
char content[] = "Hello, file.";
if(!check_file_test(fileName))
{
generate_file_test(fileName);
}
write_into_file(fileName, content);
cout << read_from_file(fileName) << endl;
return 0;
}