System calls using c++ (unix)

+1 Joe money · February 7, 2015
Hi, I am trying to write my own version of the "ls" command which lists files in a directory. 
1. If no command line arguments are given, the current directory is listed. By default, any file starting whose first character is “.” will not be listed unless the hidden flag is set. // Here is my problem. I keep showing the hidden files when i run my program
2. An optional flag, -h (for hidden), may be specified which will list all files or directories including those that start with a “.” // I am also trying to figure out how to do this.
If anyone can help me hide these hidden files I would very much appreciate it.
my code:







[
#include
#include
#include

using namespace std;

int main(void) {
 struct dirent *ent;
DIR *dir = opendir(".");
   if(dir) {
       struct dirent *ent;
       while((ent = readdir(dir)) != NULL)
       {
           cout d_name) d_name[0]== '.' ))  {

cout d_name)


Post a Reply

Replies

Oldest  Newest  Rating
0 Joe money · February 8, 2015
#include 
#include
#include

using namespace std;

int main(void) {
 struct dirent *ent;
DIR *dir = opendir(".");
   if(dir) {
       struct dirent *ent;
       while((ent = readdir(dir)) != NULL)
       {
           cout d_name) d_name[0]== '.' ))  {

cout d_name)
0 Mathias Frits Rørvik · February 8, 2015
Um, large chunks of your code is missing, also there are syntax errors. If you have trouble with the code tags ([ cøde ][ /cøde ]), you can use pastebin.com
0 Mathias Frits Rørvik · February 8, 2015
Anyway, I decided to write my own version. Feel free to use this code however you want.


#include <iostream>
#include <dirent.h>

int list_directory(std::string dirName, bool showHidden)
{
   DIR * dir = opendir("."); //open

   if(dir == nullptr) {
       return -1; //opendir failed
   }

   struct dirent * reader;

   while ((reader = readdir(dir)) != nullptr) {
//only print the filename if it is not hidden OR if showHidden is true
       if (reader->d_name[0] != '.' || showHidden) {
           std::cout << reader->d_name << std::endl;
       }
   }

   return closedir(dir); //close, may return -1 if opendir fails

}

int main(int argc, char *argv[])
{
   list_directory(".", false);
   return 0;
}
  • 1

C++

107,253 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator