【发布时间】:2010-11-12 15:40:45
【问题描述】:
我对@987654321@ 很陌生,所以我确定我做错了,但这让我很困惑。
我的代码应该从用户那里获得一个标题,并在路由目录中创建一个具有该名称的文件夹。仅当我在 makeFolder() 实现上设置断点时它才有效。出于某种原因,在我单击 continue 之前稍作休息使其工作(我正在使用 Xcode)。
不起作用我的意思是它正确返回 0 但没有创建文件夹。
这是我第一次尝试用 C 做任何事情,我只是在胡乱学习它。
编辑非常感谢您的回答和 cmets。它现在按预期工作,我在此过程中学到了一些东西。你们都是学者和先生们。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#define MAX_TITLE_SIZE 256
void setTitle(char* title) {
char *name = malloc (MAX_TITLE_SIZE);
printf("What is the title? ");
fgets(name, MAX_TITLE_SIZE, stdin);
// Remove trailing newline, if there
if(name[strlen(name) - 1] == '\n')
name[strlen(name) - 1] = '\0';
strcpy(title, name);
free(name);
}
// If I set a breakpoint here it works
void makeFolder(char * parent, char * name) {
char *path = malloc (MAX_TITLE_SIZE);
if(parent[0] != '/')
strcat(path, "/");
strcat(path, parent);
strcat(path, "/");
//strcat(path, name);
//strcat(path, "/");
printf("The path is %s\n", path);
mkdir(path, 0777);
free(path);
}
int main (int argc, const char * argv[]) {
char title[MAX_TITLE_SIZE];
setTitle(title);
printf("The title is \'%s\'", title);
makeFolder(title, "Drafts");
return 0;
}
【问题讨论】:
-
当它不“工作”时会发生什么?
-
这里一个可能的问题是,在
makeFolder中,您使用strcat附加到“路径”,但您从未向路径写入任何内容以确保它是一个以空结尾的字符串与垃圾数据相反。不知道为什么断点会产生任何影响,但是在malloc之后尝试*path = 0;,将数据的第一个字符设置为 nul 终止符。strcat的第一个参数必须是一个以 nul 结尾的字符串,否则strcat无法找到它的结尾以便追加。 -
您有很多不必要的
malloc电话。一个简单的char path[MAX_TITLE_SIZE]就可以了。 -
@aschepler 为了更清晰,我已经对其进行了编辑
-
响应您的编辑 - 当然,垃圾数据也可能包含 0 字节,因此附加了
strcat,但随后您尝试创建一个名称不可能的目录,因为垃圾数据包含不允许的字符。