0

I am having difficulty finding a way to open and read all files in a specific directory and also i don´t understand the relation between -> and pointers. I am able to easily operate with files when I know their name, but I haven't found a way to do it when I don't. As I said above what I want to do is read all the files (of a known directory) and store strings of those files in variables.

scan a directory to find files in c was referenced but my knowledge isn't enough to understand most of those commands, so if it is possible to do such a thing in a simpler way, please help

Bellow you can find the code I used to read a specific file.

    printf("Insert the name of the product to look for: ");
    char tmp_prodname4[50];
    scanf(" %[^\n]%*c",tmp_prodname4);
    char filenameProd4[50];
    char fullpathProd4[200];
    char cwdProd4[200];
    char pathProd4[200];

    if (getcwd(cwdProd4, sizeof(cwdProd4)) == NULL)
    {
        erro();
        produtos(tmpUsername,tmpPassword);
    }
    strcat(cwdProd4,"\\products\\");
    strcpy(pathProd4, cwdProd4);
    strcpy(filenameProd4, strcat(strlwr(tmp_prodname4), ".txt"));
    strcpy(fullpathProd4, strcat(pathProd4, filenameProd4));
    if( access( fullpathProd4, F_OK ) != 0 )
    {
        erro();
        produtos(tmpUsername,tmpPassword);
    }
    else //When i can access
    {
        clrscr();
        authFileProdC = fopen(fullpathProd4,"r");
        fscanf(authFileProdC, "Name: %s\n", p.nome);
        fscanf(authFileProdC, "Reference: %s\n", p.referencia);
        fscanf(authFileProdC, "Quantity in X: %d\n",&p.quantidade[1]);
        fscanf(authFileProdC, "Quantity in Y: %d\n",&p.quantidade[2]);
        fscanf(authFileProdC, "Quantity in Z: %d\n",&p.quantidade[3]);
        fscanf(authFileProdC, "Price: %fEUR.unid\n",&p.precoporunidade);
        fclose(authFileProdC);
Souz4x
  • 45
  • 5
  • 1
    If that doesn't help then you need to describe what you don't understand more specifically than "my knowledge isn't enough to understand". – kaylum Jan 25 '21 at 21:46
  • OT: Don't check if the file exists with `access` before `fopen`. Just check if `fopen` succeeds. – Jabberwocky Jan 25 '21 at 21:56

0 Answers0