C语言:popen()与fread()? [英] C Language: popen() with fread()?

查看:768
本文介绍了C语言:popen()与fread()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经坚持了几天,这真的令人沮丧.

I've been stuck on this for a few days and it's getting really frustrating.

我正在使用popen()来调用命令行进程,并获取其输出并将其存储在C字符串中.我正在使用fgets(),但似乎在换行后中断,所以我正在使用fread().唯一的问题是,返回的C字符串有时会弄乱.

I'm using popen() to call a command line process and get its output and store it in a C string. I was using fgets() but it seems that breaks after a new line, so I'm using fread(). The only problem is that the returned C string is sometimes messed up.

这是我的代码:

const char *cmd = "date";//This the shell command
char buf[BUFSIZ];//Output of the command
FILE *ptr;
int c;

if ((ptr = popen(cmd, "r")) != NULL)
     while(fread(buf, sizeof(buf),1, ptr))
          while ((c = getchar()) != EOF)
               printf("output = %s", buf);

(void) pclose(ptr);

最终的C字符串有时其中包含不应该存在的怪异字符,或者有时甚至没有字符串可用.有人可以帮忙吗? ):

The final C string sometimes has weird characters in it that shouldn't be there, or sometimes no string is even available. Can anybody please help? ):

这是我在使用fgets()时所做的事情Shell命令可以是任何可以输出文本的命令.不只是日期".

Here is what I was doing when using fgets() The Shell command can be anything that outputs text though. Not just "date."


if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
printf("output = %s", buf);
(void) pclose(ptr);

推荐答案

好吧,fgets是正确的方法.

FILE *ptr;

if (NULL == (ptr = popen(cmd, "r"))) {
    /* ... */
}

while(fgets(buf, sizeof(buf), ptr) != NULL) {
    /* There is stuff in 'buf' */
}

我认为fgets对您不起作用的原因是您做错了事.

I think the reason fgets wasn't working for you is that you were doing something wrong.

现在,这就是为什么我认为您在使用当前代码时遇到麻烦的原因:

Now, here's why I think you are running into trouble with your current code:

  • 您没有检查实际返回了多少fread
  • 您正在阅读getchar并丢弃东西
  • 缓冲区中没有NUL终止符
  • You are not checking how much fread actually returned
  • You are reading with getchar and discarding stuff
  • You don't have a NUL terminator in the buffer

正确解决这个问题,一切都会更好: fread在法律上可能读起来比您告诉的要少.

Get this right and it will all be better: fread might legally read less than you told it to.

这篇关于C语言:popen()与fread()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆