Search code examples
cwindowsstring-concatenationc-strings

Create directory and save output files in that directory


I want to create a directory with variable name like "folder Iteration Number %d, Iteration" and after that save text output in that folder.

Here is my code, the program makes the directory correctly but doesn't save the file in that, error occurs at the last line.

I have tried this

fp1 = fopen("D:\\Courses\\filename1.plt", "w"); 

For the last line and it works but I want to write file in the specific folder that I have created.

char directionname[120];
sprintf(directionname, "Profile Iteration Number_%d", it);
mkdir(directionname);
char filename1[120];
sprintf(filename1, "Velocity Profile Iteration_%d.plt", it);
FILE * fp1;
fp1 = fopen("D:\\Courses\\directionname\\filename1.plt", "w"); 

Solution

  • fp1 = fopen("D:\\Courses\\directionname\\filename1.plt", "w");
    

    It looks like from the above, that you're expecting directionname and filename1 to be replaced by variables with those names. That isn't how strings work.

    You got things mostly right when you create the directory, but you don't appear to be in the right place when you run your program, so it'll create the new directory in your current directory not under "D:\Courses\". So you should change directionname to include the full path to where you want your new directory.

    char directionname[120];
    sprintf(directionname, "D:\\Courses\\Profile Iteration Number_%d", it);
    mkdir(directionname);
    

    And then you want to prepend the filename with that value like this

    char filename1[120];
    sprintf(filename1, "%s\\Velocity Profile Iteration_%d.plt", directionname, it);
    

    filename1 should now contain someting like "D:\Courses\Profile Iteration Number_1\Velocity Profile Iteration_1.plt" which should allow you to open it like so...

    FILE * fp1;
    fp1 = fopen(filename1, "w");