I am very new to C , so I'm sure I'm doing inconvenience, but it puzzles me.
My code should get a header from the user and create a folder in the route directory with that name. It only works if I set a breakpoint in the implementation of makeFolder() . For some reason, taking a little rest before I click continue makes it work (I use Xcode).
It does not work, I mean that it correctly returns 0, but the folder is not created.
This is one of my first attempts to do anything with C , and I just messed around with it, trying to learn it.
Edit Thank you very much for your answers and comments. Now it works as expected, and I learned a bit of it. You are all scientists 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; }
source share