使用c++对文件进行操作
zhuyucheng6046 · · 科技·工程
在
1. freopen
这个函数可以对文件进行输入输出操作。
函数原型:FILE *freopen( const char *filename, const char *mode, FILE *stream )。
filename:需要重定向到的文件名或文件路径。
mode:代表文件访问权限的字符串。
mode:位置所要写的:
| 字母 | 意义 |
|---|---|
| " |
只读访问 |
| " |
只写访问 |
| " |
追加写入 |
stream:需要被重定向的文件流。
文件流形式:
| 意义 | ||
|---|---|---|
| " |
从指定文件读取 | |
| " |
从指定文件写入 | |
| " |
从指定文件追加写入 | |
| " |
标准错误输出( |
返回值:如果成功,则返回该指向该输出流的文件指针,否则返回为 NULL 。
这个函数是
试例:
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
int main(){
cout<<"请重命名文件"<<endl;
// 旧文件名
string oldName = "0.txt";
// 新文件名
string newName ;
cin>>newName;
// 使用rename函数更改文件名
if (rename(oldName.c_str(),newName.c_str()) != 0) {
cerr << "文件重命名失败" << endl;
}
cout << "文件重命名成功" << endl;
return 0;
}
注意事项
1.oldname和newname必须是有效的路径。
2.如果newname已存在,rename()函数将失败并返回
3.在rename()函数需要管理员权限才能重命名受保护的文件或目录。
3.remove
remove()函数用于删除指定的文件。
函数原型:int remove(char *filename);
filename为要删除的文件名,可以为一目录。如果参数filename 为一文件,则调用unlink()处理;若参数filename 为一目录,则调用rmdir()来处理。
函数返回值
成功则返回errno。
函数错误码
1.EROFS 欲写入的文件为只读文件。
2.EFAULT 参数filename 指针超出可存取内存空间。
3.ENAMETOOLONG 参数filename 太长。
4.ENOMEM 核心内存不足。
5.ELOOP 参数filename 有过多符号连接问题。
6.EIO I/O 存取错误。
例子
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
namespace fs = std::filesystem;
int main(){
fs::path filename = "0.txt";
// 尝试删除文件
if (fs::remove(filename)) {
cout << "文件删除成功。" << endl;
} else {
cout << "文件删除失败。" << endl;
}
return 0;
}
4.ListFilesInDirectory
这个函数用于读取指定目录下的所有文件,并将文件名输出。
示例:
#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
void listFilesInDirectory(const std::string& directoryPath) {
if (fs::exists(directoryPath) && fs::is_directory(directoryPath)) {
for (const auto& entry : fs::directory_iterator(directoryPath)) {
std::cout << entry.path() << std::endl;
}
} else {
std::cerr << "Directory does not exist or is not a directory." << std::endl;
}
}
int main() {
std::string directoryPath = "path/to/your/directory";//在“”中输入你要查文件名的目录
listFilesInDirectory(directoryPath);
return 0;
}