Ubuntu 20.04下C程序IO重定向失效,输出文件为空问题排查
IO重定向失效导致输出文件为空的问题排查
问题描述
本人编写的C代码可正常运行,但在Ubuntu 20.04环境下尝试使用IO重定向时失败。已创建输入文件test1.in,期望将结果输出至test1.out,但程序运行后test1.out为空,代码如下:
#include <stdio.h> #define MAX_STR_SIZE 80 /*******************************************************/ int my_strcmp(char[], char[]); int my_strncmp(char[], char[], unsigned int); int my_strchr(char[], int); /*******************************************************/ int main(){ int test = 0, running = 1; char str1[MAX_STR_SIZE]; char str2[MAX_STR_SIZE]; char c; int count; printf("\nLet's start testing!"); while(running){ printf("\n Enter 1: to test my_strcmp(), 2: to test my_strncmp(), 3: to test my_strchr()"); scanf("%d",&test); switch(test){ case 1: /*my_strcmp test*/ printf("\n***my_strcmp*** TEST"); printf("\nEnter first string: "); scanf("%s",str1); printf("Enter second string: "); scanf("%s",str2); printf("\nThe result is: %d\n",my_strcmp(str1, str2)); break; case 2: /*my_strncmp test*/ printf("\n***my_strncmp*** TEST"); printf("\nEnter first string: "); scanf("%s",str1); printf("Enter second string: "); scanf("%s",str2); printf("Enter maximal number of bytes to compare: "); scanf("%d",&count); printf("\nThe result is: %d\n",my_strncmp(str1, str2, count)); break; case 3: /*my_strchr test*/ printf("\n***my_strchr*** TEST"); printf("\nEnter string to search into: "); scanf("%s",str1); printf("Enter character to find: "); scanf(" %c", &c); printf("\nThe result is: %d\n",my_strchr(str1, c)); break; default: /*bad test flag*/ printf("\nERROR: Entered number is not one of those: 1,2,3 while test is running\n"); break; } printf("Should we continue? 0 to exit, 1 to continue"); scanf("%d", &running); } return 0; }
问题原因及解决办法
核心原因
标准输出缓冲机制差异
终端输出时,printf采用行缓冲,换行符\n会触发缓冲刷新;但重定向到文件时,默认是全缓冲模式,只有缓冲区填满或程序显式刷新时,内容才会写入文件。如果程序未执行到退出步骤(比如卡在输入等待),缓冲内容不会写入文件,导致test1.out为空。输入文件内容不匹配交互流程
程序是交互式设计,需要按顺序输入测试选项、字符串/参数、是否继续等内容。若test1.in的内容格式不符合程序预期的交互顺序,程序会卡在某个scanf等待输入,无法执行到输出结果的步骤。
解决步骤
强制刷新输出缓冲
在每个输出结果的printf语句后添加fflush(stdout);,确保内容立即写入文件。例如:printf("\nThe result is: %d\n",my_strcmp(str1, str2)); fflush(stdout); // 添加该行其他输出结果的位置同理添加。
确保输入文件格式正确
以测试my_strcmp为例,test1.in的内容需严格匹配交互流程:1 hello world 0依次对应:选择测试1、输入第一个字符串、输入第二个字符串、选择退出程序。
使用正确的重定向命令
编译程序后,执行以下命令完成重定向:./your_program < test1.in > test1.out替换
your_program为实际的可执行文件名。
内容的提问来源于stack exchange,提问作者l3xandrr
相关产品推荐
相关产品推荐

