【发布时间】:2017-04-16 20:46:09
【问题描述】:
我想知道如何在 C 中使用系统调用 read() 和 write()。 我正在尝试将目录中预先存在的文件的内容读入缓冲区(数组),以便我可以逐步遍历数组并确定读取的文件类型。我已经查看了很多关于此事的不同帖子,但无法弄清楚我哪里出错了。我试图在底部打印出我的缓冲区数组,以确保它在单步执行文件以确定文件类型之前保存文件的正确内容,但缓冲区什么也没有。任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char *argv[])
{
char *currentDir = NULL;
DIR *myDir = NULL;
struct dirent *myFile = NULL;
struct stat myStat;
const void *buf [1024];
int count;
int currentFile;
if (strcmp(argv[1], "ls") == 0 && argc < 3)
{
currentDir = getenv("PWD");
myDir = opendir(currentDir);
while ((myFile = readdir(myDir)) != NULL)
{
if (myFile->d_name[0] != '.')
{
puts(myFile->d_name);
//printf("%s\n", myFile->d_name);
}
}
closedir(myDir);
}
if (strcmp(argv[1], "ls") == 0 && strcmp(argv[2], "-t") == 0)
{
currentDir = getenv("PWD");
myDir = opendir(currentDir);
while ((myFile = readdir(myDir)) != NULL)
{
if (myFile->d_name[0] != '.')
{
printf("%s\n", myFile->d_name);
stat (myFile->d_name, &myStat);
printf("Last Accessed:\t%s\n", ctime(&myStat.st_atime));
printf("Last Modified:\t%s\n", ctime(&myStat.st_mtime));
printf("Last Changed:\t%s\n", ctime(&myStat.st_ctime));
}
}
closedir(myDir);
}
if (strcmp(argv[1], "ls") == 0 && strcmp(argv[2], "-f") == 0)
{
currentDir = getenv("PWD");
myDir = opendir(currentDir);
while ((myFile = readdir(myDir)) != NULL)
{
//while (count = read(0, buf, 100) > 0)
//{
//}
//write (1, buf, 100);
//printf ("Buffer Holds:\n %s\n", buf);
if (myFile->d_name[0] != '.')
{
while (count = read(myFile->d_name, buf, 100) > 0)
write (1, buf, count);
printf ("Buffer Holds:\n %s\n", buf);
}
}
}
return 0;
}
【问题讨论】:
-
“无法弄清楚我哪里出错了。”好吧。你还没有说什么是错的。请阅读How to Ask。
-
您能否准确解释一下您认为此循环的作用以及您认为
read()和write()的参数是什么(每个参数)? gist.github.com/84dac9dc427af987c0a6bee7a7b87477 -
我认为 read 没有正确地从 myFile->d_name 指定的文件中传输位,这反过来又导致 write 没有将任何内容传输到缓冲区中。我确信 while 循环
while ((myFile = readdir(myDir)) != NULL)正在逐步遍历目录,直到到达最后一个文件后所有文件都已“列出”,readdir 返回 0 表示目录中没有其他项目。所以我想如果我可以读取单个文件,将其写入缓冲区,对所述文件进行分类,然后 while 循环将再次迭代,允许我对所有文件进行分类,直到没有剩余。
标签: c system-calls