博客
关于我
Linux fprintf的用法
阅读量:219 次
发布时间:2019-02-28

本文共 1282 字,大约阅读时间需要 4 分钟。

一、fprintf 函数描述

fprintf函数用于格式化打印和输出数据,可将输出数据写入指定的流文件中。该函数根据格式字符串format,格式化数据并将结果输出到指定流stream中,直到遇到终止字符'\0'为止。

函数声明:

  • int fprintf(FILE* stream, const char* format, [argument])

参数说明:

  • stream:指向FILE对象的指针,表示输出数据流。
  • format:格式化字符串,可包含嵌入格式标签(如%[flags][width][.precision][length]specifier).
  • [argument]:可选的参数列表,用于替换format中的格式标签.

Linux系统提供五种标准流:

  • stdin:标准输入流(文件描述符0)
  • stdout:标准输出流(文件描述符1)
  • stderr:标准错误流(文件描述符2)
  • stdprn:标准打印机流
  • stdaux:标准串行设备流
  • stderr的优先级高于stdout,适用于输出调试信息时的高优先级输出。

    二、shell 输出重定向

    stdin、stdout和stderr并非只能来自键盘或屏幕,它们可以被重定向到磁盘文件或其他设备。常见的重定向方式包括:

  • 使用`>`符号进行输出重定向,例如:
  • $ ./run > output.log
  • 使用`>>`符号进行追加式重定向:
  • $ ./run >> output.log

    运行脚本时,正常日志会输出到指定文件中,但错误信息仍会输出到屏幕。例如:

  • 将正常日志和错误日志分别重定向到不同的文件:
  • $ ./run > output.log 2> error.log
  • 将错误日志与正常日志合并:
  • $ ./run > output.log 2>&1

    三、程序中输出重定向

    在程序中实现输出重定向可通过`freopen`函数完成。该函数用于重新打开文件流,并将指定的标准流(如stdin、stdout、stderr)指向新的文件。

    函数声明:

    • FILE* freopen(const char *filename, const char *mode, FILE* stream);

    参数说明:

    • filename:要打开的文件名。
    • mode:文件打开模式,与`fopen`函数中的模式一致。
    • stream:目标流(如stdin、stdout、stderr)

    使用示例:

    # 将stdin重定向到文件  freopen("data.in", "r", stdin);  将stdout输出到文件 freopen("data.out", "w", stdout); 将stderr重定向到日志文件 if (freopen("err.log", "w", stderr) == NULL) { fprintf(stderr, "error redirecting stderr\n"); }

    注意:在使用`freopen`后,需确保正确关闭重定向的文件,以避免资源泄漏。可使用`fclose`函数关闭重定向的文件和标准流。

    转载地址:http://xuwp.baihongyu.com/

    你可能感兴趣的文章
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>
    org/hibernate/validator/internal/engine
    查看>>
    SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
    查看>>
    ORM sqlachemy学习
    查看>>
    Ormlite数据库
    查看>>
    orm总结
    查看>>
    os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
    查看>>
    os.system 在 Python 中不起作用
    查看>>
    OSCACHE介绍
    查看>>
    SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
    查看>>
    OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
    查看>>
    OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
    查看>>
    OSError: no library called “cairo-2“ was foundno library called “cairo“ was foundno library called
    查看>>
    Osgi环境配置
    查看>>