如何从控制台文本保存到一个字符串中的C(Windows平台) [英] How to save text from console to a string in C (Windows platform)

查看:133
本文介绍了如何从控制台文本保存到一个字符串中的C(Windows平台)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建设一个控制台应用程序为学校项目,我真的需要这个功能,我的应用程序。

I'm currently building a console app for a school project and I really need this function for my app.

我怎么都来自控制台的文本保存到C(Windows平台)?

How do I save all the text from console to a string in C (Windows platform)?

例如:

如果我使用的功能系统(目录),它将输出到控制台,并列出所有的子目录和文件的目录。我希望它被保存在供以后使用的字符串。

If I used the function system("dir"), it will output to console and list all the subdirectories and files in a directory. And I want it to be saved on a string for later use.

推荐答案

您可以使用的 的popen() 而非系统()

#include <stdio.h>
#include <limits.h>

int main()
{
    FILE *fp;
    char path[PATH_MAX];

    fp = popen("DIR", "r");
    if (fp == NULL)
    {
        /* Handle error */
    }

    while (fgets(path, PATH_MAX, fp) != NULL)
    {
        printf("%s", path);
    }

    pclose(fp);
    return 0;
}

这篇关于如何从控制台文本保存到一个字符串中的C(Windows平台)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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