gpt4 book ai didi

c - 使用循环计数器命名文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:53:11 24 4
gpt4 key购买 nike

如何编写在循环中运行并使用循环计数器 k 为文件命名的这一行?

int k;
for(k = 0; k < 10; k++)
fopen("/home/ubuntu/Desktop/" + k + ".txt", "w"); // java-like code

另外,我如何在本地目录上创建一个文件夹以将文件放在那里而不是使用桌面?

最佳答案

您的问题分为两部分:创建目录和写入编号文件。尝试以下操作(已更新,以便明确设置目录保护,包含正确的 header ,并且在打开下一个文件之前关闭一个文件):

#include <stdio.h>
#include <sys/stat.h>

int main(void) {
const char* myDirectory = "/Users/floris/newDirectory";
char fileName[256];
int ii, fErr;
FILE *fp;
fErr = mkdir(myDirectory, (mode_t)0700);
for(ii=0; ii< 10; ii++) {
sprintf(fileName, "%s/file%d.txt", myDirectory, ii);
if((fp = fopen(fileName, "w"))!=NULL) {
// do whatever you need to do
}
else {
printf("could not open %s\n", fileName);
}
fclose(fp);
}
return 0;
}

关于c - 使用循环计数器命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com