gpt4 book ai didi

c++ - 无法使用 seekdir() 设置流位置

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:58 25 4
gpt4 key购买 nike

据我所知,seekdir 必须设置当前流位置。但是,如果我设置它 - 它会为下一个 readdir 之后的任何位置参数返回相同的 d_name。我只想读取手动输入位置的目录名称,不想使用带有 readdir 的循环

#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
using namespace std;

int main(int argc, char* argv[])
{
if(argc > 1)
{
DIR* directory = opendir(argv[1]);
if (directory == NULL)
{
cout << "Enter valid directory name" << endl;
return -1;
}

long position = 0;
cout << "Enter position of directory stream: ";
cin >> position;

seekdir(directory, position);

dirent *dir = readdir(directory);

cout << dir->d_name <<":"<< strlen(dir->d_name) << endl;
closedir(directory);

return 0;
}
else
{
return -1;
}
}

最佳答案

来自 POSIX 标准

The seekdir() function shall set the position of the next readdir() operation on the directory stream specified by dirp to the position specified by loc. The value of loc should have been returned from an earlier call to telldir(). The new position reverts to the one associated with the directory stream when telldir() was performed.

If the value of loc was not obtained from an earlier call to telldir(), or if a call to rewinddir() occurred between the call to telldir() and the call to seekdir(), the results of subsequent calls to readdir() are unspecified.

换句话说,您不能将 seekdir 与您让用户输入的位置一起使用。只有从 telldir 返回的值。所以你只需要编写那个循环。

关于c++ - 无法使用 seekdir() 设置流位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16326203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com