Hello,
I would like to recursive copy of specific files in C language in Unix? I would like to copy all the *.txt, *.nfo, *.dat, *.tex,... files (plain text) with keeping the directory (to mkdir on target).
Here my current attempt. Basic example.
mkdir does create a dir
chdir change the directory
ncp to copy a file
and the recursive is herewith:
Please feel free to start C coding discussion.
It is almost done, using above code... let's look how to make it easily. The simpler the better here.
Thank you and looking forward to reading your posts.
I would like to recursive copy of specific files in C language in Unix? I would like to copy all the *.txt, *.nfo, *.dat, *.tex,... files (plain text) with keeping the directory (to mkdir on target).
Here my current attempt. Basic example.
mkdir does create a dir
chdir change the directory
ncp to copy a file
and the recursive is herewith:
Code:
#include <stdio.h>
#if defined(__linux__)
#define MYOS 1
#elif defined(_WIN32)
#define MYOS 2
#elif defined(_WIN64)
#define MYOS 3
#elif defined(__unix__)
#define MYOS 4
#define PATH_MAX 2500
#else
#define MYOS 0
#endif
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
char path[1024];
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
printf("%*s[%s]\n", indent, "", entry->d_name);
listdir(path, indent + 2);
} else {
printf("%*s- %s\n", indent, "", entry->d_name);
}
}
closedir(dir);
}
int main(void) {
listdir(".", 0);
return 0;
}
Code:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
FILE *source, *target; int ch ;
source = fopen( argv[ 1 ], "r");
if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
target = fopen( argv[ 2 ] , "w");
if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
printf("Source: %s\n", argv[ 1 ] );
printf("Target: %s\n", argv[ 2 ] );
printf("Copying...\n");
while( ( ch = fgetc(source) ) != EOF )
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
return 0;
}
Please feel free to start C coding discussion.
It is almost done, using above code... let's look how to make it easily. The simpler the better here.
Thank you and looking forward to reading your posts.