gpt4 book ai didi

c++ - ftell 总是返回 -1

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

我正在尝试编写一个函数,该函数将按字符串中的程序名称终止实例

unsigned int kill_all_program_instances(const char * program_name){
int res;
char buf[1024];
string first;
string second;
int lSize, pid , pos;
string command="pidof ";
FILE *fd;
memset(buf,'\0',sizeof(buf));
fd=popen((command+program_name).c_str(),"r");
unsigned int mypid = getpid();
if(fd != NULL){
fseek (fd , 0 , SEEK_END);
lSize = ftell(fd);
rewind (fd);
if (lSize <= 0)
{
printf("lsize is %d\n",lSize);
pclose(fd);
return 0;
}
.....
}

这只是函数的开始,但我总是为 lSize 得到 -1。我跑了

pidof chromium-browse

得到了

26487 19353 16993 11504 10960 10880 10868 10829 10825 10805 8607 8263 8154 8089 7764 3965 3950

但是当我运行的时候

kill_all_program_instances('chromium-browse')

对于 lSize,我仍然得到 -1。

知道我的代码有什么问题吗?

谢谢

最佳答案

除了有关检测 popen 错误的评论/答案(这似乎不正确),我相信实际问题是您正在尝试在管道上使用 fseek/ftell,这不是一个有效的操作。管道不是传统意义上的"file",它是一个数据流,其中每个数据项只能读取一次。

只需使用 fscanf() 或类似的东西阅读,直到它给你一个 EOF。

关于c++ - ftell 总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16958105/

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