I'm very new to C
so I'm sure I am doing loads wrong however this is puzzling me.
My code should get a title from the user and create a folder in the route directory with that name. It only works if I set a breakpoint on the makeFolder()
implementation. For some reason that small rest before I click continue
makes it work (I'm using Xcode).
By doesn't work I mean it returns 0 correctly but no folder is created.
This is one of my first attempts at doing anything with C
and I'm just messing around trying to learn it.
Edit Many thanks for your answers and comments. It is now working as expected and I learned a little along the way. You are all scholars and gentlemen.
#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;
}