Thread: Open and read all files in specific folder to store text in variables

  1. #1
    Registered User
    Join Date
    Jan 2021
    Posts
    4

    Open and read all files in specific folder to store text in variables

    I am having difficulty finding a way to open and read all files in a specific directory. 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 the text (parts of it) of those files in variables.
    Bellow you can find the code I used to read a specific file.

    Code:
    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);
    Thank you for your time!

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    3,993
    Your code look like it is written for Windows; is this correct?
    Because there are differences between file handling in Windows and Linux!

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Jan 2021
    Posts
    4
    Quote Originally Posted by stahta01 View Post
    Your code look like it is written for Windows; is this correct?
    .
    It is Windows correct

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,085
    Code:
    HANDLE hFind;
    WIN32_FIND_DATA FindFileData;
     
    if((hFind = FindFirstFile("C:/some/folder/*.txt", &FindFileData)) != INVALID_HANDLE_VALUE){
        do{
            printf("%s\n", FindFileData.cFileName);
        }while(FindNextFile(hFind, &FindFileData));
        FindClose(hFind);
    }
    FindFirstFile
    FindNextFile
    The best argument against democracy is a five minute conversation with the average voter. - Churchill

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,593
    > Prod4
    When people start putting numbers on the ends of variables, it's usually a sign of something going wrong with the way the code is being written.

    I'm wondering if there are several other 'Prod' variables all in this same function - perhaps even just a single main() several hundred lines long.

    If so, the code needs some reorganisation into functions before it gets really out of hand.


    > 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]);
    Is your structure member this?
    int quantidade[3]

    If it is, then you're writing outside your array.
    The subscripts should be 0,1,2 not 1,2,3
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jan 2021
    Posts
    4
    Quote Originally Posted by john.c View Post
    Code:
    HANDLE hFind;
    WIN32_FIND_DATA FindFileData;
     
    if((hFind = FindFirstFile("C:/some/folder/*.txt", &FindFileData)) != INVALID_HANDLE_VALUE){
        do{
            printf("%s\n", FindFileData.cFileName);
        }while(FindNextFile(hFind, &FindFileData));
        FindClose(hFind);
    }
    FindFirstFile
    FindNextFile

    Hi, thank you for your reply! I will try to implent this code, will have to look up a few things regarding HANDLE type first but I will let you know how it goes.

  7. #7
    Registered User
    Join Date
    Jan 2021
    Posts
    4
    Quote Originally Posted by Salem View Post
    > Prod4
    When people start putting numbers on the ends of variables, it's usually a sign of something going wrong with the way the code is being written.

    I'm wondering if there are several other 'Prod' variables all in this same function - perhaps even just a single main() several hundred lines long.

    If so, the code needs some reorganisation into functions before it gets really out of hand.


    > 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]);
    Is your structure member this?
    int quantidade[3]

    If it is, then you're writing outside your array.
    The subscripts should be 0,1,2 not 1,2,3
    Regarding the naming of variables:
    For me this is a very big program (1000+lines, i know that for more expirienced programmers this is almost nothing) and there are many similar functions that need similar variables (regarding paths) but that are not the same, I just put a number in the end of those so I could keep track of what is what.

    Regarding my main xD:
    Code:
    int main(){
        setlocale(LC_ALL, "Portuguese");
    
    
        clrscr();
    
    
        showtime();
    
    
        printf("|--------------------------------------------------------------------|\n");
        printf("|                           LOJA ONLINE                              |\n");
        printf("|--------------------------------------------------------------------|\n");
        printf("| 1 - REGISTAR                                                       |\n"); //register
        printf("| 2 - INICIAR SESSÃO                                                 |\n"); //login
        printf("| 0 - TERMINAR PROGRAMA                                              |\n"); //exit
        printf("|--------------------------------------------------------------------|\n");
    
    
        printf(" Selecione a opção pretendida: "); //Select option:
        scanf("%d", &option);
        printf("\n");
    
    
        switch (option){
        case 1:
            registerUser();
            break;
    
    
        case 2:
            login();
            break;
    
    
        case 0:
            printf("\n");
            printf("|--------------------------------------------------------------------|\n");
              //Program finished successfully
            printf("|                  PROGRAMA TERMINADO COM SUCESSO!                   |\n");
            printf("|--------------------------------------------------------------------|\n");
            exit(0);
        default:
            erro();
            main();
        }
    
    
        return 0;
    }
    Regarding the index of the array:
    You are totally right! I should play more attention to that

    Thank you for the many tips!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 10-25-2020, 08:17 AM
  2. Replies: 11
    Last Post: 04-17-2013, 03:45 PM
  3. Replies: 3
    Last Post: 06-24-2011, 04:12 AM
  4. Read text file, scan and store data into variables?
    By wisdom30 in forum C Programming
    Replies: 8
    Last Post: 04-18-2011, 11:23 PM
  5. How to open a text file in a specific directory
    By codemania in forum C++ Programming
    Replies: 7
    Last Post: 07-26-2009, 05:35 PM

Tags for this Thread