Click to See Complete Forum and Search --> : System Calls
nicokiki
05-02-2004, 05:13 PM
Hi !!!
I'm argentinian so i might have gramatical or spelling errors.
Well, this is the problem i have:
i'm doing an application used in a LAN that shares files and transmit them using sockets. I have no problems with sockets but i don't know how to get the files i have in a directory. That means:
The user tells the app the directory to share with the other users. Now, with the directory i have to get the files and their info (I'm using stat function to get the size of the file, date of last modification, etc), but i can't solve my basic problem, getting the list of files of a directory.
I hope u understood me, and waiting suggestions,
Nicolas
bwkaz
05-02-2004, 05:59 PM
opendir()
readdir(), readdir(), readdir(), ...
closedir()
;)
If you don't know how to use them already (I'm going to assume you don't, since you're asking), take a look at their manpages. man 3 opendir for example. You'll need the <dirent.h> header. Basically, you create a DIR pointer, set it to the result of opendir(), and pass it to each of the other functions. readdir() will then give you a pointer to a struct dirent that contains, among other things, the name of the file.
Of course, I could ask why do this when NFS, Samba, heck even FTP, etc. already exist and will do the job just as well, but I think I'll refrain. ;)
nicokiki
05-02-2004, 08:52 PM
Thank u!!!!
Now i have a last question, how do i get the type of a file, i mean, in GNU/LINUX the extension of a file doesn't mean anything (for example: if a file is named "hi.txt", that doesn't represent a "text" file).
Bye
Nicolas
bwkaz
05-02-2004, 09:46 PM
stat() gives you the permissions on the file, which will tell you whether or not it's executable.
Other than that... you'd probably have to look up the magic number for each of the file types you wanted to support. Look for that magic number at whichever byte offset in the file, and if you find it, then it's that type of file.
That's how the file command works, anyway...
GaryJones32
05-03-2004, 02:50 AM
I had to edit this like 4 times just to get out the obvious typos
so like everything i do it's all wrong but you get the idea !
char* dir_path; //end with a slash
DIR* dir;
size_t path_len = strlen(dir_path);
struct dirent* entry;
struct stat buf;
struct stat st;
char entry_path[PATH_MAX +1];
dir = opendir(dir_path);
while ((entry = readdir(dir))) != NULL) {
const char* type;
strncpy(entry_path + path_len , entry->d_name, sizeof(entry_path) - path_len);
// stat will tell about permissions
// S_IWUSR S_IRGRP S_IXOTH and like that
stat (entry_path, &buf);
if (buf.st_mode & S_IXUSR)
printf("user has executable permission for '%s' .\n", entry_path)
// lstat will tell about type
//S_ISDIR S_ISLNK S_ISCHR S_ISBLK S_ISFIFO S_ISSOCK S_ISREG
lstat (entry_path, &buf);
if (S_ISDIR (st.st_mode))
printf( "'%s' is a directory. \n", entry_path );
}
closedir(dir);