Open directory using C
I am accepting the path through command line input.
it doesn’ t enter the loop. i.e dir==null .
How do I pass the command line input to dir pointer?
4 Answers 4
You should really post your code (a) , but here goes. Start with something like:
You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp
Note also that you have to pass a directory in, not a file. When I execute:
That’s because it’s a file rather than a directory (though, if you’re sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).
(a) This has now been rectified but, since this answer has been accepted, I’m going to assume it was the issue of whatever you were passing in.
Some feedback on the segment of code, though for the most part, it should work.
- int main — the standard defines main as returning an int .
- c and args are typically named argc and argv , respectfully, but you are allowed to name them anything
- You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn’t. There’s no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy .
If this returning NULL , it can be for a few reasons:
- The directory didn’t exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory , which will fail, because it tries to opendir(«my») )
- You lack permissions to the directory
- There’s insufficient memory. (This is unlikely.)
plain C: opening a directory with fopen()
I have a program which opens a file and checks its length.
Now, at least under Linux, fopen() returns a valid file descriptor when opening a directory. This results in the seek operation returning -1 (or, as size_t is unsigned, 0xFFFFFFFFFFFFFFFF =2 64 -1 on a 64-bit system).
Unfortunately, the condition in the above code ( flen == ((size_t)-1) ) does not catch that case, neither does flen == 0xFFFFFFFF (EDIT: should be 0xFFFFFFFFFFFFFFFF ). printf() -Commands with %x ord %d as format string show that both sides of the comparison should have the same value.
Why does the comparison operator behave in such a strange way, even when both sides are of the same type ( size_t )? I am using gcc 4.8.1 as compiler.
2 Answers 2
Directories do not exist in the C99 standard (or the C2011 one). So by definition, fopen -ing a directory is either implementation specific or undefined behavior.
fopen(3) can fail (giving a NULL result). fseek(3) can also fail (by returning -1). And then you should preferably check errno(3) or use perror(3)
ftell is documented to return a long , and -1L on failure. On 64 bits Linux this is 0xffffffffffffffff .
You code should be instead
BTW, On Linux/Debian/Sid/AMD64 with libc-2.17 and 3.10.6 kernel, that codes runs ok when argv[1] is /tmp ; surprizingly, flen is LONG_MAX i.e. 0x7fffffffffffffff
BTW, on Linux, directories are a special case of files. Use stat(2) on a file path (and fstat on a file descriptor, perhaps obtained with fileno(3) from some FILE* ) to know more meta data about some file, including its «type» (thru its mode). You want opendir(3), readdir(3) & closedir(3) to operate on directory contents. See also inode(7).
Linux C read a directory
Hello I want to read from and write to a directory just like reading from and writing to files. I always use the open , read , write and close functions, which means I use descriptors. But doing this on a directory doesn’t work, the open call works, but read returns -1 and errno is EISDIR. Am I forced to use streams to read a directory?
2 Answers 2
The read() and write() system calls cannot be used on directories. Instead, the getdents() / getdents64() system calls are used to read a directory. Directories cannot be directly written at all.
Futhermore, glibc does not provide a wrapper for the getdents() / getdents64() system calls — instead it provides the POSIX-conforming readdir() function, which is implemented using those system calls. Most programs should use readdir() , but it is possible to call the system calls directly using syscall() .
I found this code here in Stack Overflow (How can I get the list of files in a directory using C or C++?), that helped me a lot in understanding how it works:
Not the answer you’re looking for? Browse other questions tagged c linux directory or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2020.9.18.37632
How to open a directory/folder and a URL through Terminal
I can navigate my files quite fast through terminal. Faster than double clicking. open. look, double click. etc.
How do I open a directory in the Ubuntu GUI? For example:
Then voila, it opens in the Ubuntu GUI as if i navigated manually?
Also, how can I open a URL in my default browser via terminal. It’d be awesome to go: F12
And Chrome opens it up.
7 Answers 7
To Open Directory:
To open a Folder from terminal type the following,
Simply typing nautilus will take you file browser,
To Open URL:
You can type any one of the following in terminal,
If you want to open two URL’s at the same time then leave some space after the first URL and type the second,
Note:
- Linux is case-sensitive, so type the file name correctly.
- You can also add an alias to short the command,for example if you need openurl instead of x-www-browser you should edit the .bashrc file
gedit
In the bottom of the file add the following lines
How to recursively list directories in C on Linux?
I need to recursively list all directories and files in C programming. I have looked into FTW but that is not included with the 2 operating systems that I am using (Fedora and Minix). I am starting to get a big headache from all the different things that I have read over the past few hours.
If somebody knows of a code snippet I could look at that would be amazing, or if anyone can give me good direction on this I would be very grateful.
5 Answers 5
Here is a recursive version:
Why does everyone insist on reinventing the wheel again and again?
POSIX.1-2008 standardized the nftw() function, also defined in the Single Unix Specification v4 (SuSv4), and available in Linux (glibc, man 3 nftw ), OS X, and most current BSD variants. It is not new at all.
Naïve opendir() / readdir() / closedir() -based implementations almost never handle the cases where directories or files are moved, renamed, or deleted during the tree traversal, whereas nftw() should handle them gracefully.
As an example, consider the following C program that lists the directory tree starting at the current working directory, or at each of the directories named on the command line, or just the files named at the command line:
Most of the code above is in print_entry() . Its task is to print out each directory entry. In print_directory_tree() , we tell nftw() to call it for each directory entry it sees.
The only hand-wavy detail above is the decision on how many file descriptors one should let nftw() use. If your program uses at most two extra file descriptors (in addition to the standard streams) during the file tree walk, 15 is known to be safe (on all systems having nftw() and being mostly POSIX-compliant).
In Linux, you could use sysconf(_SC_OPEN_MAX) to find the maximum number of open files, and subtract the number you use concurrently with the nftw() call, but I wouldn’t bother (unless I knew the utility would be used mostly with pathologically deep directory structures). Fifteen descriptors does not limit the tree depth; nftw() just gets slower (and might not detect changes in a directory if walking a directory deeper than 13 directories from that one, although the tradeoffs and general ability to detect changes vary between systems and C library implementations). Just using a compile-time constant like that keeps the code portable — it should work not just on Linux, but on Mac OS X and all current BSD variants, and most other not-too-old Unix variants, too.
In a comment, Ruslan mentioned that they had to switch to nftw64() because they had filesystem entries that required 64-bit sizes/offsets, and the «normal» version of nftw() failed with errno == EOVERFLOW . The correct solution is to not switch to GLIBC-specific 64-bit functions, but to define _LARGEFILE64_SOURCE and _FILE_OFFSET_BITS 64 . These tell the C library to switch to 64-bit file sizes and offsets if possible, while using the standard functions ( nftw() , fstat() , et cetera) and type names ( off_t etc.).
c++ list all directories and subdirectories within in (LINUX ) [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 7 years ago .
I am new in c ++ . could someone please give me some code of how to get all directories and all it’s subdirectories RECURSIVELY in LINUX. i haven’t found anything on internet that could help me ( or code that works.) I need to get all files withing folder and it;s subfolder.
IN UBUNTU I don’t have getfiles, directories.
6 Answers 6
Recursively apply the same algorithm you applied to the top-level directory.
Recursion is unnecessary. There is a facility on Linux to do this iteratively.
The ftw() function calls the supplied callback for every file and directory in the given tree.
In addition of Dmitri’s answer, you might be interested in using the nftw library function which «does the recursion for you»
Use nftw . It provides various options to fine-tune the directory traversal.
That page also shows an example.
The answers on listing directories are only the first part of the answer but i didnt see anyone answering the recursive part. To recursively do anything you have to create a subroutine that «calls itself» — note that you should take care when dealing with symbolic links especially in cases like /exports when using nfs, that could lead to circular recursion and lock you in an infinte loop! Basically:
this isn’t real code, its pseudo-code to try to help you get a better idea of how the recursion works without confusing you with language this idea can be applied in any language that has some sort of call-return mechanism which these days is just about every language i can think of
notice how if the entries do not contain any real directories, the function doesn’t call itself? this is important because this is how infinite recursion is avoided. Be warned however you might want to make it so this operation can be cancelled, larger filesystems these days can take a lot of time to process. The way I usually do it is to start another thread and do the search in the background, and have the background thread check for a cancellation flag in case the user wants to stop the operation, and so it can post information about how much time is left, percentage complete, etc ,etc. its a bit crude but this should get anyone interested in this type of thing going in the right direction. And remember to ALWAYS properly check for errors and place exception handling, this is something that I see new programmers skip ALL the time.