问题描述
我对Linux很陌生,所以请多多包涵。我有3个问题。 我创建了一个程序,将命令行参数作为文件名,然后输出这些文件的信息,类似于ls命令。第一个问题是,它仅报告来自程序文件本身的第一个命令行参数的信息。如果我添加更多命令行参数,它将继续仅在第0个参数文件上报告。
我的第二个问题是,如果没有给出命令行参数,则我将列出当前目录中所有文件的文件信息。鉴于没有给出命令行参数,我不知道如何在程序中利用stat来实现。
我的第三个问题是使用timespec结构检索文件的上次访问,修改和状态时间。我改用本地时间,但是如何使用timespec检索这些时间呢?
我的代码:
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
int main(int argc,char *argv[])
{
int i;
struct stat buf;
char *ptr;
char *acc;
for(i = 1; i < argc; i++){
stat(argv[i],&buf);
time_t t;
struct tm *tmp;
time(&t);
tmp = localtime(&t);
char buf1[64];
char buf2[64];
char buf3[64];
struct passwd *pw = getpwuid(buf.st_uid);
struct group *gr = getgrgid(buf.st_gid);
if(S_ISREG(buf.st_mode))
{
ptr = "Regular";
}
else if(S_ISDIR(buf.st_mode))
{
ptr = "Directory";
}
else if(S_ISCHR(buf.st_mode))
{
ptr = "Character special";
}
else if(S_ISBLK(buf.st_mode))
{
ptr = "Block special";
}
else if(S_ISFIFO(buf.st_mode))
{
ptr = "FIFO";
}
else if(S_ISLNK(buf.st_mode))
{
ptr = "Symbolic Link";
}
else if(S_ISSOCK(buf.st_mode))
{
ptr = "Socket";
}
else
{
ptr = "UnkNown file type";
}
printf("File name: \t %s\n",argv[i]);
printf("User name: \t %s \n",pw->pw_name);
printf("Group name: \t %s \n",gr->gr_name);
printf("File type: \t %s\n",ptr);
printf("File access: \t");
if(access(argv[1],R_OK) == 0)
{
if(ptr == "Directory")
{
printf("-dr");
}
else
{
printf("-r");
}
}
if(access(argv[1],W_OK) == 0)
{
printf("w");
}
if(access(argv[1],X_OK) == 0)
{
printf("x\n");
}
printf("File size: \t %ld bytes \n",(long) buf.st_size);
printf("I-node: \t %ld \n",(long) buf.st_ino);
printf("Device: \t %d,%d \n",major(buf.st_dev),minor(buf.st_dev));
printf("Links: \t %ld \n",(long) buf.st_nlink);
strftime(buf1,64,"Last access: \t %a %b %d %X %Y \n",tmp);
printf("%s\n",buf1);
strftime(buf1,"Last modification: \t %a %b %d %X %Y \n","Last status: \t %a %b %d %X %Y \n",buf1);
}
exit(0);
}
到目前为止,我的代码:
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)