我想知道如何在 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;
}
最佳答案
这里还需要一些括号:
while (count = read(myFile->d_name, buf, 100) > 0)
尝试:
while ((count = read(myFile->d_name, buf, 100)) > 0)
另外,建议使用 sizeof:
while ((count = read(myFile->d_name, buf, sizeof(buf))) > 0)
但是您已将 buf
声明为指针数组:
const void *buf [1024];
这似乎不太可能是您真正想要的。文件中是否真的存储了指针值?我认为您可能想让 buf
成为一个字符数组:
char buf[1024];
关于c - C 中的系统调用 read 和 write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923757/