[英]Linux “ls -al” like program in C
我必須寫一個C程序來做家庭作業,它的作用類似於Linux的“ ls -al”命令。 我知道互聯網上有很多示例程序可以滿足我的需求,但是我有一個特定的問題,無法找到解決方案。 我還想提到,我是C編程的新手。 這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
int list_dir(const char *dirname) {
struct dirent* current_directory;
struct stat my_stat;
struct tm lt;
struct passwd *pwd; // For User-ID
DIR* directory = opendir(dirname);
if(directory == NULL) {
printf("list_dir : %s : %s \n", dirname, strerror(errno));
return 0;
}
printf("Directory : %s\n", dirname);
printf("\n");
while( (current_directory = readdir(directory) ) ) {
stat(current_directory->d_name, &my_stat);
if ( (stat(current_directory->d_name, &my_stat) ) == 0 ) {
pwd = getpwuid(my_stat.st_uid); // Get User-ID
}
// Last Modified
time_t t = my_stat.st_mtime;
localtime_r(&t, <);
char timebuf[80];
strftime(timebuf, sizeof(timebuf), "%c", <);
if (pwd != 0) {
printf("%s \t %ld \t %s \t %s", pwd->pw_name, (long)my_stat.st_size, timebuf, current_directory->d_name);
printf("\n");
} else {
printf("%d \t %ld \t %s \t %s", my_stat.st_uid, (long)my_stat.st_size, timebuf, current_directory->d_name);
printf("\n");
}
}
closedir(directory);
return 0;
}
int main(int argc, char* argv[]) {
if ( argc == 1 ) {
return list_dir ( "." );
} else {
int ret = 0;
for (int i = 1; i < argc; i += 1 ) {
if ( list_dir ( argv[i] ) != 0 ) {
ret = 1;
}
}
return ret;
}
}
該程序必須顯示與“ ls -al”相同的內容(沒有權限)。 到目前為止,如果我使用“ gcc -std = gnu99 -o list_dir list_dir.c”進行編譯,並使用“ ./list_dir”執行程序,那么我得到的結果與“ ls -al”相同,看起來像這樣:
username 1599 Fri May 1 20:43:57 2015 list_dir.c
但是,如果我使用類似“ ./list_dir / home / username / Downloads /”的程序運行該程序,則會得到以下信息:
32727 0 Sun May 8 07:09:04 4461391 selection_sort.c
如您所見,該程序無法獲得有關用戶名,文件大小和年份的正確信息。 由於if(pwd!= 0)語句的else情況,該信息也出現了。 如果我沒有其他情況,則該程序僅打印出文件,可以獲取正確的信息。 另外,如果我刪除此if語句以及if語句:
if ( (stat(current_directory->d_name, &my_stat) ) == 0 )
我遇到了細分錯誤。
所以我的問題是:1.我在做什么錯。 我知道我做錯了,因為作為作業的提示,我有一個示例程序運行,並且還提示我可以使用“ stat,lstat,readlink,getpwnam,getpwuid,strftime”。
2.是否有任何方法可以通過stat()和用戶ID來獲取用戶名,或者只能通過getpwuid來獲取用戶名?
這里,
if ( (stat(current_directory->d_name, &my_stat) ) == 0 ) {
pwd = getpwuid(my_stat.st_uid); // Get User-ID
}
如果stat()
失敗怎么辦? pwd
將具有未初始化的值或先前迭代設置的不正確的值。
stat
失敗的原因, current_directory->d_name
僅包含文件名,而stat
需要完整路徑。 因此,您需要在文件名前添加目錄名,並將其傳遞給stat()
。 您現在僅傳遞文件名。
就像是:
char buf[1024];
errno = 0;
snprintf(buf, sizeof buf, "%s/%s", dirname, current_directory->d_name);
if ( (stat(buf, &my_stat) ) == 0 ) {
...
}
else {
printf("%s: %s\n", buf, strerror(errno));
// exit here or continue to the next entry in the directory
//depending how you wish to handle failure
}
並在stat()
失敗的情況下處理錯誤。
循環中還有一個stat()
,它什么也沒做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.