Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. C language Help using Dirent.h

C language Help using Dirent.h

Scheduled Pinned Locked Moved C / C++ / MFC
helpquestion
25 Posts 4 Posters 4 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A a random user

    it seems that the problem is within these lines for (int i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { if (secSpot != spot) { secSpot++; } if (secSpot == spot) { if (flag == 0) { location = i; flag++; } } } } _flushall(); char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char)*location); int a; a = strlen(entrenceToTheFolderBefore); printf("%d", a); for (int i = 0; i < location; i++) { entrenceToTheFolderBefore[i] = argv[1][i]; } when the entrenceToTheFolderBefore has the size of 40 bits and not 23 like it was suppsoe to the argv that im using is C:/Users/win7/Desktop/1/C2_Mid_Anti - Virus_Project.zip

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #10

    Sorry, but that code does not make any sense. I have no idea what the first block of code is supposed to be doing. And in the code following the flushall call, you have made a call to strlen on a pointer returned from malloc. But the memory that it points to has not been initialised with a string, so the value you get will be either zero, or some random invalid number. You must use strlen on the source string (argv[1]) in order to measure it. So your code should be something like:

    int length = strlen(argv[1]) + 1; // extra space for trailing null character
    char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char) * length);
    for (int i = 0; i < length; i++)
    {
    entrenceToTheFolderBefore[i] = argv[1][i];
    }

    You could use strcpy here, but perhaps your teacher has told you not to.

    A 1 Reply Last reply
    0
    • L Lost User

      Sorry, but that code does not make any sense. I have no idea what the first block of code is supposed to be doing. And in the code following the flushall call, you have made a call to strlen on a pointer returned from malloc. But the memory that it points to has not been initialised with a string, so the value you get will be either zero, or some random invalid number. You must use strlen on the source string (argv[1]) in order to measure it. So your code should be something like:

      int length = strlen(argv[1]) + 1; // extra space for trailing null character
      char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char) * length);
      for (int i = 0; i < length; i++)
      {
      entrenceToTheFolderBefore[i] = argv[1][i];
      }

      You could use strcpy here, but perhaps your teacher has told you not to.

      A Offline
      A Offline
      a random user
      wrote on last edited by
      #11

      I dont know if i fixed it or not because Just now i saw your comment but this is how far i got in order to get to the second frole from the first file but for some odd reason it stopps when i do malloc #include #include #include "dirent.h" int main(int argc, char** argv) { DIR* OtherDir; struct dirent *OtherEnt; int location = 0, flag = 0, secSpot = 0, argvSize, spot = 0,i; argvSize = strlen(argv[1]); for (i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { spot++; } } puts(argv[1]); for (i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { if (secSpot != spot) { secSpot++; } if (secSpot == spot) { if (flag == 0) { location = i; flag++; } } } } char* UnwantedName = (char*)malloc(NULL); //<--- problem for (int i = location + 1; i < argvSize; i++) { strcat(UnwantedName,"/C2_Mid_Anti-Virus_Project.zip"); } _flushall(); char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char)*location); for (int i = 0; i < location; i++) { entrenceToTheFolderBefore[i] = argv[1][i]; } _flushall(); OtherDir = opendir(entrenceToTheFolderBefore); char* notPath1 = (char*)malloc(NULL); char* notPath2 = (char*)malloc(NULL); strcpy(notPath1, argv[1]); strcpy(notPath2, argv[1]); strcat(notPath1, "/."); strcat(notPath2, "/.."); char* InfectedFolderPath = (char*)malloc(NULL); while (OtherEnt = readdir(OtherDir)) { if ((strcmp(OtherEnt->d_name, UnwantedName) != 0 && (strcmp(UnwantedName, notPath1) != 0) && (strcmp(UnwantedName, notPath2) != 0))) { strcpy(InfectedFolderPath, entrenceToTheFolderBefore); strcat(InfectedFolderPath, "/"); strcat(InfectedFolderPath, OtherEnt->d_name); puts(InfectedFolderPath); } } free(UnwantedName); free(entrenceToTheFolderBefore); free(InfectedFolderPath); free(notPath1); free(notPath2); }

      L 1 Reply Last reply
      0
      • A a random user

        I dont know if i fixed it or not because Just now i saw your comment but this is how far i got in order to get to the second frole from the first file but for some odd reason it stopps when i do malloc #include #include #include "dirent.h" int main(int argc, char** argv) { DIR* OtherDir; struct dirent *OtherEnt; int location = 0, flag = 0, secSpot = 0, argvSize, spot = 0,i; argvSize = strlen(argv[1]); for (i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { spot++; } } puts(argv[1]); for (i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { if (secSpot != spot) { secSpot++; } if (secSpot == spot) { if (flag == 0) { location = i; flag++; } } } } char* UnwantedName = (char*)malloc(NULL); //<--- problem for (int i = location + 1; i < argvSize; i++) { strcat(UnwantedName,"/C2_Mid_Anti-Virus_Project.zip"); } _flushall(); char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char)*location); for (int i = 0; i < location; i++) { entrenceToTheFolderBefore[i] = argv[1][i]; } _flushall(); OtherDir = opendir(entrenceToTheFolderBefore); char* notPath1 = (char*)malloc(NULL); char* notPath2 = (char*)malloc(NULL); strcpy(notPath1, argv[1]); strcpy(notPath2, argv[1]); strcat(notPath1, "/."); strcat(notPath2, "/.."); char* InfectedFolderPath = (char*)malloc(NULL); while (OtherEnt = readdir(OtherDir)) { if ((strcmp(OtherEnt->d_name, UnwantedName) != 0 && (strcmp(UnwantedName, notPath1) != 0) && (strcmp(UnwantedName, notPath2) != 0))) { strcpy(InfectedFolderPath, entrenceToTheFolderBefore); strcat(InfectedFolderPath, "/"); strcat(InfectedFolderPath, OtherEnt->d_name); puts(InfectedFolderPath); } } free(UnwantedName); free(entrenceToTheFolderBefore); free(InfectedFolderPath); free(notPath1); free(notPath2); }

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #12

        It would help if you formatted your code properly with <pre> tags around it, and removed the extra blank lines. The following is wrong, you cannot malloc nothing.

        char* UnwantedName = (char*)malloc(NULL); //<--- problem

        You must provide the size, in bytes, that you want to allocate, like

        char* UnwantedName = (char*)malloc(argvSize);

        A 2 Replies Last reply
        0
        • L Lost User

          It would help if you formatted your code properly with <pre> tags around it, and removed the extra blank lines. The following is wrong, you cannot malloc nothing.

          char* UnwantedName = (char*)malloc(NULL); //<--- problem

          You must provide the size, in bytes, that you want to allocate, like

          char* UnwantedName = (char*)malloc(argvSize);

          A Offline
          A Offline
          a random user
          wrote on last edited by
          #13

          I tried editing it to char* entrenceToTheFolderBefore =(char*)malloc(sizeof(char)*location); but it still triggers a break point

          A 1 Reply Last reply
          0
          • A a random user

            I tried editing it to char* entrenceToTheFolderBefore =(char*)malloc(sizeof(char)*location); but it still triggers a break point

            A Offline
            A Offline
            a random user
            wrote on last edited by
            #14

            this is odd it seems that after switching place wit hthe malloc above it was ok

            A 1 Reply Last reply
            0
            • L Lost User

              It would help if you formatted your code properly with <pre> tags around it, and removed the extra blank lines. The following is wrong, you cannot malloc nothing.

              char* UnwantedName = (char*)malloc(NULL); //<--- problem

              You must provide the size, in bytes, that you want to allocate, like

              char* UnwantedName = (char*)malloc(argvSize);

              A Offline
              A Offline
              a random user
              wrote on last edited by
              #15

              Now that I fixed most of the code the last part is which is the loop to find out the name of the second folder Reminder that The argv has a path to a folder the program is trying to exit the folder to the fodler before (succeeded) and now at the last part trying to get the path for the second folder and the file before if it makes any sence so for some odd reason it doesnt work the weirder part is when i try to do puts(); on the Dir struct d_name and it triggers break point

              //UnwatedName = /C2_Mid_Anti-Virus_Project.zip notPath1 = '.' notPath2=".."

              while (OtherEnt = readdir(OtherDir))
              {

              puts(OtherEnt->d\_name);
              
              if ((OtherEnt->d\_name != UnwantedName) && (OtherEnt->d\_name != notPath1) && (OtherEnt->d\_name != notPath2))
              {
                  puts(OtherEnt->d\_name);
                  strcpy(InfectedFolderPath, entrenceToTheFolderBefore);
                  strcat(InfectedFolderPath, "/");
                  strcat(InfectedFolderPath, OtherEnt->d\_name);
                  puts(InfectedFolderPath);
              
              }
              

              }

              1 Reply Last reply
              0
              • A a random user

                this is odd it seems that after switching place wit hthe malloc above it was ok

                A Offline
                A Offline
                a random user
                wrote on last edited by
                #16

                Go to ParentNow that I fixed most of the code the last part is which is the loop to find out the name of the second folder Reminder that The argv has a path to a folder the program is trying to exit the folder to the fodler before (succeeded) and now at the last part trying to get the path for the second folder and the file before if it makes any sence so for some odd reason it doesnt work the weirder part is when i try to do puts(); on the Dir struct d_name and it triggers break point Hide Copy Code //UnwatedName = /C2_Mid_Anti-Virus_Project.zip notPath1 = '.' notPath2=".." while (OtherEnt = readdir(OtherDir)) { puts(OtherEnt->d_name); if ((OtherEnt->d_name != UnwantedName) && (OtherEnt->d_name != notPath1) && (OtherEnt->d_name != notPath2)) { puts(OtherEnt->d_name); strcpy(InfectedFolderPath, entrenceToTheFolderBefore); strcat(InfectedFolderPath, "/"); strcat(InfectedFolderPath, OtherEnt->d_name); puts(InfectedFolderPath); } }

                L 1 Reply Last reply
                0
                • A a random user

                  Go to ParentNow that I fixed most of the code the last part is which is the loop to find out the name of the second folder Reminder that The argv has a path to a folder the program is trying to exit the folder to the fodler before (succeeded) and now at the last part trying to get the path for the second folder and the file before if it makes any sence so for some odd reason it doesnt work the weirder part is when i try to do puts(); on the Dir struct d_name and it triggers break point Hide Copy Code //UnwatedName = /C2_Mid_Anti-Virus_Project.zip notPath1 = '.' notPath2=".." while (OtherEnt = readdir(OtherDir)) { puts(OtherEnt->d_name); if ((OtherEnt->d_name != UnwantedName) && (OtherEnt->d_name != notPath1) && (OtherEnt->d_name != notPath2)) { puts(OtherEnt->d_name); strcpy(InfectedFolderPath, entrenceToTheFolderBefore); strcat(InfectedFolderPath, "/"); strcat(InfectedFolderPath, OtherEnt->d_name); puts(InfectedFolderPath); } }

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #17

                  You cannot use != to compare strings, you need to use strcmp. If you are going to append a new directory name to an existing path then you need to allocate the sum of, the length of each string, plus 1 for the extra backslash, plus 1 for the trailing null. I would strongly suggest you get some decent learning materials and study the basics of the C language and standard libraries, before continuing with this somewhat advanced project.

                  A 1 Reply Last reply
                  0
                  • L Lost User

                    You cannot use != to compare strings, you need to use strcmp. If you are going to append a new directory name to an existing path then you need to allocate the sum of, the length of each string, plus 1 for the extra backslash, plus 1 for the trailing null. I would strongly suggest you get some decent learning materials and study the basics of the C language and standard libraries, before continuing with this somewhat advanced project.

                    A Offline
                    A Offline
                    a random user
                    wrote on last edited by
                    #18

                    to be honest the first thing i used was strcmp i tried to do so many combinatiosn and in so many different ways that im out of ideas so i tried anything that could might help

                    L 1 Reply Last reply
                    0
                    • A a random user

                      to be honest the first thing i used was strcmp i tried to do so many combinatiosn and in so many different ways that im out of ideas so i tried anything that could might help

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #19

                      That is what I guessed from looking at all your posts. And that is why I suggested you stop trying random pieces of code, and go and work through some tutorials and reference guides on the basics of C and its run-time libraries. Trying to learn programming from posting questions here is really not a good idea. A few, or many, hours of serious study will serve you much better in the long term.

                      A 1 Reply Last reply
                      0
                      • L Lost User

                        That is what I guessed from looking at all your posts. And that is why I suggested you stop trying random pieces of code, and go and work through some tutorials and reference guides on the basics of C and its run-time libraries. Trying to learn programming from posting questions here is really not a good idea. A few, or many, hours of serious study will serve you much better in the long term.

                        A Offline
                        A Offline
                        a random user
                        wrote on last edited by
                        #20

                        you have been very helpfull to me and believe it or not im so close to finish the first exercise of the project as you adviced I will study the materials again but it will be after I will hand it out because I have left a few more hours to work on it till it hits 11:50 pm

                        A 1 Reply Last reply
                        0
                        • A a random user

                          you have been very helpfull to me and believe it or not im so close to finish the first exercise of the project as you adviced I will study the materials again but it will be after I will hand it out because I have left a few more hours to work on it till it hits 11:50 pm

                          A Offline
                          A Offline
                          a random user
                          wrote on last edited by
                          #21

                          im sorry to bother you again but my time is not very short and I have no where else to go I combined the 2 codes i made into 1 but i keep getting now an error on the first function on the while How do i fix it? http://pastebin.com/p52qeXix[^]

                          1 Reply Last reply
                          0
                          • A a random user

                            well.. im trying to open a folder with an unknown number of programs using argv and argc through the cmd to the adress of the folder i need to use the dirent.h and maybe the FILE struct to open the files the code needs to open each file and search the text within (it has mp3 signatures etc) in a binary way and search through it with a second file that the text inside of it is not in any place in there in other words i need to spot if the second file's signature is nto repeatign anywhere on the other files this is the far that i got but im stuck can anyone help me?

                            #include <stdio.h>
                            #include <stdlib.h>
                            #include "dirent.h"

                            int main(int argc, char** argv){

                            int count = 0, size = 0;
                            int sizes\[3\];
                            FILE \*log = fopen("C:\\\\Users\\\\win7\\\\Desktop\\\\1\\\\C2\_Mid\_Anti-Virus\_Project.zip\\\\AntiVirusLog.txt", "wt");
                            DIR \*dir;
                            struct dirent \*ent;
                            int found = 0;
                            
                            /\* Open directory \*/
                            
                            dir = opendir(argv\[1\]);
                            
                            
                            
                            while ((ent = readdir(dir)))
                            {
                                count++;
                            
                            
                                sizes\[0\] = strlen(argv\[1\]);
                                sizes\[1\] = 2;
                                sizes\[2\] = strlen(ent->d\_name);
                                size += sizes\[0\] + sizes\[1\] + sizes\[2\] + 1;
                            
                                char\* string = (char\*)malloc(sizeof(char)\*size);
                                \_flushall();
                                strcpy(string,argv\[1\]);
                                strcat(string, "\\\\");
                                strcat(string, ent->d\_name);
                            
                                FILE\* youtube = fopen (string, "rb");
                            
                                if (youtube != NULL)
                                {
                                    print("success \\n");
                                }
                            
                                puts(ent->d\_name);
                            }
                            
                            
                            
                            
                            
                            fclose(log);
                            closedir(dir);
                            
                            
                            
                            return 0;
                            

                            }

                            D Offline
                            D Offline
                            David Crow
                            wrote on last edited by
                            #22

                            a random user wrote:

                            well.. im trying to open a folder with an unknown number of programs

                            You mean files?

                            a random user wrote:

                            this is the far that i got but im stuck

                            So what is your code (not) doing? Be specific, as "im stuck" is all sorts of vague.

                            "One man's wage rise is another man's price increase." - Harold Wilson

                            "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                            "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                            1 Reply Last reply
                            0
                            • A a random user

                              thank you but atm im trying to figure out how to open the folder that contains the folder that I entered in argv because its a fodler inside a folder that contains files as you can see it doesnt work int count = 0, size = 0, totalDirs = 0,location = 0; int sizes[3],flag = 0; int secSpot = 0; int argvSize, spot = 0; char c; argvSize = strlen(argv[1]); for (int i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { spot++; } } for (int i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { if (secSpot != spot) { secSpot++; } else if ((secSpot == spot) && (flag == 0)) { location = i; flag++; } } } location--; char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char)*location); for (int i = 0; i < location; i++) { entrenceToTheFolderBefore[i] = argv[1][i]; } puts(entrenceToTheFolderBefore); free(entrenceToTheFolderBefore);

                              D Offline
                              D Offline
                              David Crow
                              wrote on last edited by
                              #23

                              a random user wrote:

                              thank you but atm im trying to figure out how to open the folder that contains the folder that I entered in argv

                              Which would be that folder's parent. I'm not sure that is what you really want to do. :confused:

                              "One man's wage rise is another man's price increase." - Harold Wilson

                              "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                              "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                              1 Reply Last reply
                              0
                              • A a random user

                                insteadof entering "\\" my teacher told me that I could use / to make it quicker my problem is tho that when I do puts i get garbage and not the output i wanted as a link outside of the argv folder

                                D Offline
                                D Offline
                                David Crow
                                wrote on last edited by
                                #24

                                a random user wrote:

                                insteadof entering "\\" my teacher told me that I could use / to make it quicker

                                Perhaps one of you did not understand the other. Whether you use one character or two, the difference in time cannot be measured.

                                "One man's wage rise is another man's price increase." - Harold Wilson

                                "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                                "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                                1 Reply Last reply
                                0
                                • A a random user

                                  thank you but atm im trying to figure out how to open the folder that contains the folder that I entered in argv because its a fodler inside a folder that contains files as you can see it doesnt work int count = 0, size = 0, totalDirs = 0,location = 0; int sizes[3],flag = 0; int secSpot = 0; int argvSize, spot = 0; char c; argvSize = strlen(argv[1]); for (int i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { spot++; } } for (int i = 0; i < argvSize; i++) { if (argv[1][i] == '/') { if (secSpot != spot) { secSpot++; } else if ((secSpot == spot) && (flag == 0)) { location = i; flag++; } } } location--; char* entrenceToTheFolderBefore = (char*)malloc(sizeof(char)*location); for (int i = 0; i < location; i++) { entrenceToTheFolderBefore[i] = argv[1][i]; } puts(entrenceToTheFolderBefore); free(entrenceToTheFolderBefore);

                                  D Offline
                                  D Offline
                                  David Crow
                                  wrote on last edited by
                                  #25

                                  Nothing personal, but this code looks all kinds of convoluted. When iterating the items in the folder pointed to by argv[1], how are you determining if an item is a file or a folder? [edit] Upon further inspection, I now see that code in dirent.h is a wrapper for this. My bad. [/edit] I suspect you need to be using the _findfirst()/_findnext() pair, or _stat() at the very minimum. It's been ages since I've used the former, but I envision something like:

                                  void processFile( const char *pFile )
                                  {
                                  // however you need to handle 'pFile' would go here
                                  }

                                  //====================================================================

                                  void processFolder( const char *pFolder )
                                  {
                                  char *p = (char *) malloc(strlen(pFolder) + 5);
                                  strcpy(p, pFolder);
                                  strcat(p, "\\*.*");

                                  struct \_finddata\_t fileinfo; 
                                  
                                  intptr\_t handle = \_findfirst(p, &fileinfo);
                                  if (handle != -1)
                                  {
                                      do
                                      {
                                          if (fileinfo.attrib & \_A\_SUBDIR)
                                          {   
                                              if (fileinfo.name\[0\] != '.')
                                                  processFolder(fileinfo.name);
                                          }
                                          else
                                              processFile(fileinfo.name);
                                          
                                      } while(\_findnext(handle, &fileinfo) == 0);
                                  
                                      \_findclose(handle);
                                  }
                                  
                                  free(p);
                                  

                                  }

                                  //====================================================================

                                  void main(int argc, char* argv[])
                                  {
                                  if (argc == 2)
                                  processFolder(argv[1]);
                                  }

                                  Obviously this does not solve your overall problem, but you can't bother with checking the contents of a file before you have successfully iterated a folder.

                                  "One man's wage rise is another man's price increase." - Harold Wilson

                                  "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                                  "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups