0

How can I create a folder as well as file inside that folder that the user specifies?

this is part of my function:

char* folder = *(argv + 2); //"C:\\Users\\User\\Desktop\\New folder";
if (!(log = fopen("folder\\file.txt", "a")))// checking if there is any problem with the file
    {
        printf("The log file has not created correctly, closing the program\n");
        system("PAUSE");
        exit(1);
    } 
ariel20
  • 15
  • 10

2 Answers2

1

Either I don't understand your question or it is too simple. Let's assume it is too simple. Then you can do this like:

char filename[1024];
FILE *logfp;
sprintf(filename, "%s\\file.txt", argv[2]);
if ((logfp=fopen(filename,"w")==NULL) {
    //...error etc.

Note: this assumes all the directories in the path exist.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
1

Not sure how you pass the arguments to the command. This assumes that the user enters only one argument that is the path to the file to be created.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc,char* argv[])
{
        char string[100]={'\0'};
        FILE* fp;
        if(argc==2)
          snprintf(string,(size_t)100,"%s\\filename",argv[1]);
        else{
          printf("Usage : .\\executable_name \"path\"");
          exit(-1);
        }
        fp=fopen(string,"a"); # Opening file in append mode.
        if (fp==NULL){
                printf("Can't create file");
                exit(-1);
        }
        else{
                fprintf(fp,"%s","teststring\n");
        }
        fclose(fp);
        return 0;
}

Run this one as :

.\executable_name "C:\Users\SomeUser"
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • When dealing with user input you should ***really*** use `snprintf()`! – alk May 12 '16 at 19:49
  • @alk : incorporated :D. By the way, I am still wondering what would be a sensible character limit for the folder depth in Windows? – sjsam May 12 '16 at 20:18
  • 1
    In general I'd go for `MAX_PATH` on Windows and (try to) go for `PATH_MAX` on UNIX, the latter however can become complicated when trying to stay portable by the nature of the different IX'ish OSes around. You might like to to read the answers on this http://stackoverflow.com/q/833291/694576 why. Please also be aware of the subtle difference between a maximum path length and the maximum length of a file name. – alk May 13 '16 at 04:41