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

问题描述:

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

directory1中

  1. text1.txt
  2. text2.txt

Directory2

  1. text1.txt
  2. text2.txt

我还没有实现的循环,但我想文件名追加到该文件夹​​,这样我可以创建文件。

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

谢谢你的帮助。

这是迄今为止

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); 
+3

'文件夹+ “的text.txt”'这是不是在C字符串和字符串连接是如何工作的。做一些关于['strcat'](http://en.cppreference.com/w/c/string/byte/strcat)函数的研究,并[获取一本好的初学者书籍](http:// stackoverflow。 COM /问题/ 562303 /对,最终-C-书指南和列表)。 –

+0

我知道那不是它如何在C中工作,但我已经尝试了strcat函数,但它覆盖了文件夹变量值。我只想暂时追加到字符串。 – LegacyBear

+0

然后你必须将第一个字符串'strcat()'的长度保存到它并使用它,然后截断它回到原来的位置,'strcat()'下一个文件等, –

我已经写了关于你的示例中的第一行代码:

char folder[] = "directory1/"; 

尾随“/”是没有必要创建目录directory1

行:

fPointer = fopen(folder + "text.txt", "w"); 

不是做你期望它做的事。 C使用字符串函数来操纵字符串,例如连接2个字符串。(#include <string.h>

给定的位置,如:

char absoluteDir[] = "/user1/dir1/dir2/"; // copy to an absolute location, or 
char relativeDir[] = "../dir1/";// will go one dir up from location and copy to dir1 

和文件名作为创建:

char filename[] = "text.txt"; 

使用的字符串的功能之一,例如strcatsprintf将组件串连接到一个位置,如

char dirPathFileName[260]; 

例如:

sprintf(dirPathFileName, "%s%s", absoultDir, filename); 

strcat(dirPathFileName, relativeDir); 
strcat(dirPathFileName, filename); 

这些将创建任一:

"/user1/dir1/dir2/text.txt" 

"../dir1/text.txt" 
(Note: this requires call be made from a location where one directory 
up contains a sub-direcotry named 'dir1`) 

这将正常工作的功能fopen

+0

是的,我已经做到了。但是,我的名声太低,无法将您的点击上传为公开 – LegacyBear

一次C类不支持+操作字符串时的第一个参数。您需要使用strcat()在C.One件事总是看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; 
} 
+0

感谢您对stat的建议。我试过strcat,但它覆盖了文件夹变量。我只需要临时使用 – LegacyBear

+0

你可以使用'sprintf()' – krpra