c++ 使用 fopen_s 创建文件
时间: 2024-10-07 14:04:57 浏览: 110
在C++中,`fopen_s`函数是`fopen`的一个安全版本,用于代替旧的、可能存在安全隐患的`fopen`函数,特别是在Windows平台下。当你想要创建一个新的文件时,你可以使用下面的格式:
```cpp
#include <cstdio>
#include <fstream>
int main() {
std::string filename = "example.txt";
char mode[] = "w"; // 或者 "a" (追加模式), "r" (读取模式)等,取决于你需要
std::FILE* file = NULL;
if (_sfsopen_s(&file, filename.c_str(), mode, _TRUNCATE) == 0) { // _sfsopen_s是Windows特有的,_TRUNCATE防止现有内容被保留
if (file != NULL) {
// 文件打开成功,你可以在这里写入数据
std::fprintf(file, "Hello, this is a new file.\n");
fclose(file); // 关闭文件
} else {
// 打开文件失败,处理错误
perror("Error opening file");
}
} else {
// 操作失败,处理安全打开失败的错误
perror("_sfsopen_s error");
}
return 0;
}
```
这里需要注意的是,`_sfsopen_s`和`fopen_s`是Windows API的一部分,而在跨平台环境下可能会有所不同。在非Windows系统上,你可能需要使用标准的`fopen`并配合适当的错误检查。
阅读全文
相关推荐


















