I have a function that (ideally) would merely simulate a portion of the ls -l command. It is meant to return permissions for the file, and the name of the file. I don't really care about any other information. It also is not the cleanest, as I am stuck using the VIM editor, and it is significantly less user friendly than modern IDEs.
Code:
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <fcntl.h> void ls_l(){ DIR *dir; struct dirent *file; struct stat fileStat; dir = opendir("./dir0"); lstat(".", &fileStat); while (((file = readdir(dir)) != NULL)){ lstat(file->d_name, &fileStat); //User permissions printf( (fileStat.st_mode & S_IRUSR) ? " r" : " -"); printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-"); printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-"); //Group permissions printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-"); printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-"); printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-"); //Other permissions printf("\n"); } } void doStep(int stepNum){ chdir("~/cs3377/project2/dir0"); switch (stepNum){ case 1: printf("Display files and permissions for ./dir0\n"); ls_l(); break; case 2: printf("Change permission for file6.txt to -rwxrwx---\n"); chmod("./file6.txt", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP); break; case 3: printf("Remove file1.txt and file2.txt from directory dir1\n"); break; case 4: printf("Remove dir1 directory\n"); break; case 5: printf("Display files and permission for ./dir0\n"); ls_l(); break; } } int main(){ for (int i = 1; i < 2; i++){ doStep(i); } return 0; }
I am only through the user and group permissions and I already have noticed a serious problem with the code. For whatever reason, the group permissions fail to change with each file, and thus do not return the correct values. I am only aware of this because because changing the permissions of a file and checking the return with ls -l gives me different values that that of my code.
I am aware that this isn't a complete program, as I am not finished with it, but it can compile and run on my school UNIX server, so it should suffice for any testing.
I would also like to not that case 2 never functioned before I noticed this error, so if you'd like to help with that as well I would appreciate it.
Edit: I use this to compile: ''' gcc task13prog.c -o task13prog '''
https://stackoverflow.com/questions/66937148/st-mode-not-returning-expected-values-for-s-ixxx-comparison April 04, 2021 at 08:56AM
没有评论:
发表评论