#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#define MAX 100
int copy(char fileName[], char dirName[])
{
printf("0");
//open directory and test if it opens successfully
DIR *OGdir = opendir("~/");
struct dirent *OGdp = readdir(OGdir);
if(OGdir == NULL)
{
printf("nUnable To Open Directoryn");
return(-1);
}
printf("1n");
//more code will go here i have more to do but this wont even work
return(0);
}
Im opening the current directory, i need to be able to open a file within it to copy it over but i cant even open the directory.
This also happens when I tried just opening the file without trying the directory. I assume it has something to do with the ssh server or something else I need to do but Ive tried so many different things and this is almost exactly how everywhere tells me to do this, am i forgetting something? is there something special I need to do since Im on my schools linux ssh server? this is my first time using ssh servers so i apologize if this is something i should know already.
1
First, you are passing OGdir
to readdir
before checking if OGdir
is not NULL
. You should check first before using the pointer at all:
if(OGdir == NULL)
{
printf("nUnable To Open Directoryn");
// return(-1);
return EXIT_FAILURE; // This a more portable way to indicate failure than the constant -1
}
struct dirent *OGdp = readdir(OGdir); // Move this line after the if
Second, opening a file/directory from code is not compatible with the use of the "~/"
notation. If you want to use the current working directory, use opendir(".");
instead. Or you could manually query the home directory.
But if you type echo ~
in the Terminal, your home directory is printed, which shows that ~
is expanded to your home directory at the command-line level, rather than at the program level.
Also, typically you do not just call readdir()
once. If at some point you want to loop through all files in a directory, I would suggest using:
struct dirent *OGdp;
while((OGdp = readdir(OGDir)) != NULL)
{
// Your code
}
And not:
struct dirent *OGdp = readdir(OGDir);
while(OGdp != NULL)
{
// Your code
OGdp = readdir(OGDir);
}
2