Create a file in another C directory

0

I have a folder containing my .c file, its executable, and another folder called Files. I need when the function below is executed the file is created in the Files folder and not in the folder where the .c and .exe are found.

char nomeDoArquivo[100] = {'
char nomeDoArquivo[100] = {'%pre%'};

printf("\nDigite o nome do arquivo: ");
scanf("%s", nomeDoArquivo);
fp = fopen(("Arquivos//%s", nomeDoArquivo),"w");
'}; printf("\nDigite o nome do arquivo: "); scanf("%s", nomeDoArquivo); fp = fopen(("Arquivos//%s", nomeDoArquivo),"w");
    
asked by anonymous 09.07.2018 / 16:28

1 answer

0

The function fopen must receive the string with the path, and you are passing ("Arquivos//%s", nomeDoArquivo) , which is not valid. In addition / is not a caratere that needs to escape and therefore does not need two // .

Building the path with folder has to be done previously, and you can do it at the expense of sprintf :

char nomeFinal[200];
sprintf(nomeFinal, "Arquivos/%s", nomeDoArquivo);

From there, just open with the generated path:

FILE *fp = fopen(nomeFinal, "w");

Please note that to work as it is the Arquivos folder must exist. As a note, if the first thing you do with nomeDoArquivo is to read through scanf , you also do not need to initialize with 'scanf' , because %code% will put the terminator.

Complete code for reference:

char nomeDoArquivo[100], nomeFinal[200];
printf("\nDigite o nome do arquivo: ");
scanf("%s", nomeDoArquivo);
sprintf(nomeFinal, "Arquivos/%s", nomeDoArquivo);
FILE *fp = fopen(nomeFinal,"w");
    
09.07.2018 / 19:21