我尝试创建一个文件,我做到了。
现在我正在尝试在一个新文件夹中创建文件,但是这段代码不起作用!
#include <stdio.h>
#include <stdlib.h>
int main( void)
{
FILE *fp;
fp = fopen("txt/example.txt", "w"); // This only works without "txt/"
fprintf(fp, "%s", "Some data here");
fclose(fp);
return 0;
}
也许我需要在文件之前和之后创建文件夹,但我不知道如何实现...感谢任何帮助!
最佳答案
此示例在创建文件之前创建目录,并且在创建文件时,注意文件名中的双 \\
以防止从 \e 尝试转义序列
,尽管它也适用于单个 /
。
#include <stdio.h>
#include <direct.h>
#include <stdlib.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
int main(void) {
FILE *fp;
if (mkdir("txt"))
fatal ("Error creating directory");
if ((fp = fopen("txt\\example.txt", "w")) == NULL)
fatal ("Error opening file");
if (fprintf(fp, "%s", "Some data here") <= 0)
fatal ("Error writing to file");
if (fclose(fp))
fatal ("Error closing the file");
return 0;
}
关于c - 如何在c中创建文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438670/