sussil
June 20, 2010, 9:26pm
1
Hi guys,
I have a question which might be easy to answer but I don't how to do it.
The thing is I need to make a program in C which creates a file with all the content from the files in \etc.
I'm not new to C language but to UNIX.
I've read somewhere I need to use functions like f_read f_write for files but I don't know how to traverse the directory and append the each file's info in the new file.
thank you in advance!!
Sussie
vbe
June 21, 2010, 4:10am
2
No so a "dummies" question...
Moved to more suitable forum: programming
sussil
June 26, 2010, 10:45am
3
So if anyone is interested about how it can be done, this works (more or less) but of course the code could be optimized.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
void listar(char *dir);
int main(int argc, char *argv[]){
int dscr1, dscr2, i;
char Buffer[512];
dscr2 = creat("file.txt", 0666);
DIR *d;
struct dirent *ent;
struct stat inode;
if((d = opendir("/etc")) == NULL){
printf("Couldn't open");
perror("\etc");
exit(1);
}
printf("\n");
chdir("/etc");
while(ent = readdir(d)){
if((strncmp(".", ent->d_name) != 0) && (strncmp("..", ent->d_name) != 0)){
lstat(ent->d_name, &inode);
if(S_ISREG(inode.st_mode)){
printf("%s\n", ent->d_name);
if((dscr1 = open(ent->d_name, O_RDONLY)) == -1){
perror("ERROR");
close(dscr1);
continue;
}
while (read(dscr1, &Buffer, 512)){
write(dscr2, Buffer, sizeof(Buffer));
}
for(i = 0; i < 512; i++){
Buffer = ' ';
}
close(dscr1);
}
}
}
printf("\n");
close(dscr2);
return 0;
}