How to create a file within the users directory?

Asked

Viewed 156 times

0

For each different pc, the Users/User folder tbm is different, I want to know how to create a file inside that directory. I was trying and I got to the following code:

FILE *bug;
    bug = fopen("%userprofile%//log//teste.txt", "w");
    fprintf(bug, "start");
    fclose(bug);

But unsuccessfully, the file is not created in the specified directory.

2 answers

1


If Voce is absolutely sure that the directory name is right Voce can "print" the error name with...

//Outros includes
//...
#include <errno.h>
int main (int argc, char const *argv[] )
{
  char* path = pegar_diretorio_e_nome_do_arquivo();
  FILE * bug = fopen(path, "w");;
  if (bug!=NULL){
    fprintf(bug, "start");
    fclose (bug);
  }
  else{
    printf("Error: %s\n", strerror(errno));
  }

  return 0;
}

In advance if you receive

//Error: No such file or directory

Your directory is wrong or maybe someone has deleted the folder so You have to create the directories again.

I created a function that does this, You only need to pass the directory and the name of Archivo

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
//
// Cria um arquivo no dir especificado 
// mesmo que o dir nao exista
//
FILE * criar_arquivo(char* diretorio, char* arquivo)
{
  // "M Aloca" as char* que serao usadas
  size_t len = (strlen(diretorio) + strlen(arquivo));
  char* fopen_cmd = (char*)malloc(sizeof(char) * len); //Comando fpoen
  strcat(fopen_cmd, diretorio);
  strcat(fopen_cmd, "/");
  strcat(fopen_cmd, arquivo);

  // O prefixo eh "system specific"
#if (__unix__ || __APPLE__)  // Caso use gnu/linux ou mac...
  char prefixo[] = "mkdir -p "; 
#else  
  char prefixo[] = "mkdir "; // Windows...(?) 
#endif
  len = (strlen(prefixo) + strlen(diretorio));
  char* mkdir_cmd = (char*)malloc(sizeof(char)* len); //Comando mkdir (criar diretorio)
  strcat(mkdir_cmd, prefixo); 
  strcat(mkdir_cmd, diretorio); 


  FILE * file = fopen (fopen_cmd, "w");
  switch (errno)
  {
  case 2: // Nao foi possivel achar o diretorio
    printf("Error: %s\n", strerror(errno));
    system(mkdir_cmd);
    file = fopen (fopen_cmd,"w");
    break;

  default: // Outro erro
    printf("Error: %s\n", strerror(errno)); //Opcional
    file = NULL; // ? exit(EXIT_FAILURE)
    break;
  }

  free(mkdir_cmd);
  free(fopen_cmd);
  return file;
}

PS: Don’t forget to check the directory name

char* diretorio = "./user\\ 5/log"; //Cria 1 pasta "user 5" com subpasta "log"
char* diretorio = "./user\\5/log"; //1 pasta   "user5" com subpasta "log"
char* diretorio = "./user\\5/ log";//Cria 2 pastas, "user5" e "log"
bug = bug = criar_arquivo(diretorio, "teste.txt");
  • 1

    Good guy, I really liked your code, you even left it to work in other So’s... Very good!!

0

Bolei uma solução simples mas funcional, para quem não é tão expert assim, mas só funciona no windows acredito... basta apenas pegar o nome de username de quem está logado no pc usando a função getenv padrão da linguagem C (stdio.h). Example: char *nomeUser = getenv("USERNAME"); so we already have the username, otherwise we just need to specify the reso of the path, which can be used by concatenating the string of the command into another variable. Example:

char *nomeUser = getenv("USERNAME");
    char comando[100] = {"C:/Users/"};
    sprintf(comando, "%s%s/Desktop", comando, nomeUser);
    printf("%s", comando);

//printf returned value: C:/Users/'User'/Desktop

Browser other questions tagged

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