gpt4 book ai didi

在 C 中使用循环创建目录和文件

转载 作者:太空狗 更新时间:2023-10-29 12:10:30 24 4
gpt4 key购买 nike

我是 C 编程的新手,所以可能有一个简单的解决方案,但我试图通过在 C 中使用循环在这些目录中创建多个目录和文件。例如,

目录1

  1. text1.txt
  2. text2.txt

目录2

  1. text1.txt
  2. text2.txt

我还没有实现循环,但我正在尝试将文件名附加到文件夹中,以便我可以创建文件。

我附上了代码,我知道错误出现在我尝试连接字符串的第 5 行。有没有办法创建一个变量来存储目录的名称,并将文件名附加到目录以创建文件?

感谢您的帮助。

这是我到目前为止编写的代码

char folder[] = "directory1/";
mkdir(folder, 0750);

//Create text file in directory
fPointer = fopen(folder + "text.txt", "w");

for(int i = 0; i < textLength; i++){
//Only return numbers from 0 - 25
int rnum = rand() % 26;
//Use uppercase ascii values therefore add 65
text[i] = (char) (rnum +65);

//Write to the file
fprintf(fPointer,"%c",text[i]);
}
//Stop writing to text.txt and close connection
fclose(fPointer);

最佳答案

首先 C 在字符串的情况下不支持 + 运算符。您需要在 C 语言中使用 strcat()连接字符串。还有一件事总是查看 stat 以进行检查 如果目录存在,和 mkdir,创建一个目录。

下面的代码有效

#include<stdio.h>
#include<stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>


int main(){

char folder[] = "directory1/";
char text[1024];
struct stat st = {0};
FILE *fPointer;

if (stat(folder, &st) == -1) {
mkdir(folder,0750);
}

//Create text file in directory
strcat(folder,"text.txt");
fPointer = fopen(folder, "w");
int len=strlen(folder);

for(int i = 0; i < len; i++){
//Only return numbers from 0 - 25
int rnum = rand() % 26;
//Use uppercase ascii values therefore add 65
text[i] = (char) (rnum +65);

//Write to the file
fprintf(fPointer,"%c",text[i]);
}
//Stop writing to text.txt and close connection
fclose(fPointer);
return 0;
}

关于在 C 中使用循环创建目录和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46612504/

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