在C中构建为树的目录

时间:2013-10-29 21:55:57

标签: c tree strcat

#include<stdio.h>
#include <string.h>
int main()
{
 /*The output file*/
FILE *fo;

/*The input file*/
FILE *fi;

/*The current character we are on*/
char c[2];
c[1]=0;

/*The array to build the word we are on*/
char *s=malloc(900000);

/* Opens the file for reading */
fi=fopen("d.txt","r");
c[0]=getc(fi);
/* While loop responsible for reading current character,
 creating the string of directories linked to that character
 , and placing the word at the end*/
while(c[0]!=EOF)
{
strcat(s,"lib\\");
/*While loop that checks the current char for a space or a newline*/
    while((c[0]!=' '&&c[0]!='\n'))
    {


       strcat(s,c);

    strcat(s,"\\");
 c[0]=getc(fi);
    }
    printf(s);
    /*Makes the directory following the string of characters (IE: Character would be c\h\a\r\a\c\t\e\r)*/
    mkdir(s);

    s=malloc(9000);
c[0]=getc(fi);

}


return 0;
}

修改

事实证明解决方案是那种:

  char *s=(char* )malloc(600);


   ...
    while(c[0]!=EOF)
    {
    strcpy(s,"lib");
    ...
    strcat(s,"\\");
        strcat(s,c);
...
mkdir(s,0777);
 printf(s);
    s=(char* )realloc(s,600);

但是,这样做并不能解决没有通过mkdir语句创建目录的问题。 修改了大多数错误,唯一的问题是减少完成所有操作所需的时间,并首先创建它本意的目录。

2 个答案:

答案 0 :(得分:0)

char c;
...
c=getc(fi);
...
strcat(s,(char*)c);

此代码无效:strcat意味着2个字符串,我们知道字符串以值0结束。

你必须做

char c[2];
c[1] = 0;
...
c[0] = getc(fi);


   ...

   strcat(s, c);

并且strcat没有realloc s,这是你为s分配好大小的责任。

修改

在你的循环结束时:s=NULL; =&gt; C!= Java。

首先,您需要使用malloc分配s,最终将其与realloc重新分配,并将其与free一起释放。 strcat不分配任何内存,它只将字符串中的字节复制到包含字符串的缓冲区。

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
 /*The output file*/
FILE *fo;

/*The input file*/
FILE *fi;

/*The current character we are on*/
char c[2];
c[1]=0;

/*The array to build the word we are on*/
char *s=(char* )malloc(100);

/* Opens the file for reading */
fi=fopen("d.txt","r");
c[0]=getc(fi);
/* While loop responsible for reading current character,
 creating the string of directories linked to that character
 , and placing the word at the end*/
while(c[0]!=EOF)
{
strcpy(s,"lib");

/*While loop that checks the current char for a space or a newline*/
    while((c[0]!=' '&&c[0]!='\n')){
mkdir(s,"w");
    strcat(s,"\\");
    strcat(s,c);
    c[0]=getc(fi);

    }

    /*Makes the directory following the string of characters (IE: Character would be c\h\a\r\a\c\t\e\r)*/

 printf(s);
    s=(char* )realloc(s,100);
c[0]=getc(fi);

}


return 0;
}