Create a file in another directory

Asked

Viewed 668 times

1

I have a folder that contains my file . c, its executable and another folder called Arquivos. I need that when the function below is executed the file is created in the folder Arquivos and not in the folder that . c and . exe are in.

char nomeDoArquivo[100] = {'\0'};

printf("\nDigite o nome do arquivo: ");
scanf("%s", nomeDoArquivo);
fp = fopen(("Arquivos//%s", nomeDoArquivo),"w");

1 answer

1

The function fopen has to receive the string with the path, and you are to pass ("Arquivos//%s", nomeDoArquivo), that is not valid. Beyond that / is not a character that needs to escape and so does not need two //.

The construction of the path with paste has to be done beforehand, and can do so at the expense of sprintf:

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

From there it is only open with the generated path:

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

Note that to work as well as the folder Arquivos must exist. As a note, if the first thing you do with nomeDoArquivo is to read through scanf, also no need to initialize with '\0', for the scanf 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");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.