用C++创建一个文件夹,并写入多个不同文件数据
时间: 2023-06-04 13:08:54 浏览: 273
您可以使用C语言中的mkdir函数来创建文件夹,和fopen函数来写入多个不同文件数据。以下是一个简单的代码示例可以帮助您实现此功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
int main()
{
char folder_name[50] = "my_folder"; // 文件夹名称
char file_names[3][20] = {"file1.txt", "file2.txt", "file3.txt"}; // 需要写入的文件名称
char file_contents[3][50] = {"This is file1 content.", "This is file2 content.", "This is file3 content."}; // 需要写入的文件内容
char path[100];
FILE *fp;
int i;
// 创建文件夹
if(mkdir(folder_name) == -1) {
printf("Unable to create directory\n");
exit(EXIT_FAILURE);
}
printf("Directory created successfully!\n");
// 写入多个文件数据
for(i = 0; i < 3; i++) {
sprintf(path, "%s/%s", folder_name, file_names[i]); // 构建完整路径
fp = fopen(path, "w"); // 打开文件,如果不存在则创建
if(fp == NULL) {
printf("Error opening file %s\n", path);
exit(EXIT_FAILURE);
}
// 写入文件内容
fprintf(fp, "%s", file_contents[i]);
// 关闭文件
fclose(fp);
printf("Content written to %s file successfully!\n", path);
}
return 0;
}
```
请注意:此示例代码仅供参考,您可能需要根据实际情况进行修改,比如增加错误处理等。