I would like to be able to do file/directory manipulation in C.
Simple and cross-platform would be great, otherwise it should work in Linux.
I tried searching the wep and looking at some man pages, but couldn't find anything useful.
I would like to be able to do file/directory manipulation in C.
Simple and cross-platform would be great, otherwise it should work in Linux.
I tried searching the wep and looking at some man pages, but couldn't find anything useful.
Did you read the FAQ here on this very site?
I don't know of a cross-platform solution but for linux look up opendir(), readdir().
Here is a link that may help.
opendir
Jim
Cross-platform isn't really necessary, I just thought maybe something existed.
I'll check out opendir().
This works, it lists all the files in the current dir:
Now I have a few questions:PHP Code:
#include <stdio.h>
#include <dirent.h>
int main()
{
DIR *dir = opendir(".");
struct dirent *dirent;
if (dir)
{
while (dirent = readdir(dir))
{
printf("%s\n", dirent->d_name);
}
}
else
{
fprintf(stderr, "error: cannot access directory\n");
}
return 0;
}
How do I get a file pointer from a dirent?
How do I tell what type of file the dirent is, and if it's a directory, recursively go in it?
> How do I get a file pointer from a dirent?
d_name is the file.
If you want to do something with the file, you'll have to open it.
> How do I tell what type of file the dirent is, and if it's a directory, recursively go in it?
Use the stat() function (see the manual page)
It has things like IS_DIR() and other macros to tell you what it is.
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.
I wrote this:
but it gives an error:PHP Code:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int main()
{
DIR *dir = opendir(".");
struct dirent *dp;
struct stat stat;
if (dir)
{
printf("\n--- %s ---\n", dp->d_name);
if (stat(dp->d_name, &stat) == 0)
{
//TODO: display stats
}
else
{
fprintf(stderr, "error: stat failed\n");
}
}
else
{
fprintf(stderr, "error: cannot access directory\n");
}
return 0;
}
Code:$ gcc test.c test.c: In function ‘main’: test.c:14:11: error: called object ‘stat’ is not a function
Because you have a variable with the same name as the function.
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.
Haven't noticed that.