我一直在使用access(file_name, 0) == -1
检查目录中是否存在用户输入file_name
。但是此方法适用于当前工作目录。
我想知道是否有一种方法我可以知道file_name
是否存在于另一个目录中,所以我可以将它移动到该目录。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/param.h>
void MoveFile(void)
{
DIR *directory;
FILE *Temp_file;
struct dirent *read_direcory;
char inserted_file_name[25]="/", intro[3]="/";
char *file_name = malloc(sizeof(*file_name));
char Current_path[200], destination_path[1024],relocating_path[1024] = "/";
int counter;
directory = opendir("./");
if (directory != NULL && getcwd(Current_path, sizeof(Current_path)) !=NULL)
{
fprintf(stdout, "\nYour current working directory: %s \n", Current_path);
counter = 0;
while ((read_direcory = readdir(directory)) != NULL){
printf("%d %s\n",counter,read_direcory -> d_name);
counter++;
}
closedir(directory);
}else{
perror("\nUnable to find the directory!");
}
printf("\nEnter just the name of the file you wish to move from above (e.g) file.txt.\n");
scanf("%s",file_name);
strcat(inserted_file_name, file_name);
printf("\nWrite the directory where %s file is located (e.g) /Users/Sam\n", file_name);
scanf("%s", relocating_path);
strcat(relocating_path, inserted_file_name);
//I want to know here whether it exists in that directory or not.
printf("\nWrite the name of the directory where you want to move your file to (e.g) /Users/Sam/Pictures:\n");
scanf("%s", destination_path);//file_name
strcat(destination_path, inserted_file_name);
if (rename(relocating_path, destination_path)){
perror(NULL);
getchar();
}
printf("\nMoving %s file was successful!:D\n", file_name);
}
答案 0 :(得分:1)
查看文件是否存在的一种方法是使用stat
系统调用:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
{
...
struct stat sb;
if (stat(destination_path, &sb) == -1) {
if (errno == ENOENT) {
// File does not exist
}
}
}