C語言編程問題文件權限的子進程
我試着去一個有一個父進程打印一個子進程,每 文件穿過作爲參數,或者如果沒有傳遞參數然後抓住當前每個文件目錄。爲所有文件打印權限。我相信問題是我的struct stat buf的位置; (目前全球)。目前我的輸出打印出文件名和目錄,但沒有權限。任何建議將不勝感激
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
void permission();
typedef int bool;
#define TRUE 1
#define FALSE 0
struct stat buf;
int main(int argc, char *argv[]) {
bool commandline = FALSE; //determine if 0 args passed
if (argc < 2){commandline=TRUE;}
struct passwd *passwd;
passwd = getpwuid(getuid());
char *file, *dir;
uid_t uid; //user id
gid_t gid; //group
uid = getuid();
gid = getgid();
DIR *d;
struct dirent *directory;
d = opendir(".");
struct stat buf;
int i,pid=1;
for (i = 1; (i < argc && pid) || (commandline==TRUE) ; i++) {
if (!(pid = fork())) {
if (argc > 1) {
dir = passwd->pw_dir;
file = malloc(sizeof(dir) + 1 + sizeof(argv[i]));
strcat(file, dir);
strcat(file, "/");
strcat(file, argv[i]);
printf("File: %s\nDirectory: %s\n", argv[i], file);
permission();
} else {
if (d) {
while ((directory = readdir(d)) != NULL) {
dir = passwd->pw_dir;
printf("File: %s\n",directory->d_name);
printf("Directory: %s/%s\n",dir, directory->d_name);
permission();
}
}
}
} /* IF CHILD */
commandline=FALSE;
} /* FOR LOOP */
while (wait(NULL) > 0);
} /* !Main */
/* PRINT FILE PERMISSIONS*/
void permission() {
int fileMode;
fileMode = buf.st_mode;
if (fileMode & S_IRUSR) {
printf("You have Owner permissions:");
if (fileMode & S_IREAD) { printf(" Read "); }
if (fileMode & S_IWRITE) { printf("Write "); }
if (fileMode & S_IEXEC) { printf("Execute"); }
printf("\n\n");
} else if (fileMode & S_IRGRP) {
printf("You have Group permissions:\n");
if (fileMode & S_IREAD) { printf(" Read "); }
if (fileMode & S_IWRITE) { printf("Write "); }
if (fileMode & S_IEXEC) { printf("Execute"); }
printf("\n\n");
} else if (fileMode & S_IROTH) {
printf("You have General permissions:");
if (fileMode & S_IREAD) { printf(" Read "); }
if (fileMode & S_IWRITE) { printf("Write "); }
if (fileMode & S_IEXEC) { printf("Execute"); }
printf("\n\n");
}
}
你能給我一個關於如何將它傳遞給permission()的示例代碼。 –
我想起了錯誤的樹叫你。你的困難並不是沒有把信息傳遞給你的功能。你的困難在於'buf'沒有數據,因爲你永遠不會用'stat'填充它。 –