gpt4 book ai didi

c - 使用 write() 读取标准输入/文件并打印行 - 不显示行数

转载 作者:行者123 更新时间:2023-11-30 14:59:51 27 4
gpt4 key购买 nike

我可以让它镜像这条线。我尝试使用 printf 打印该行,但不起作用,因为它已缓冲并且仅在我 Ctrl+D 时打印。

我正在尝试使用 write() 但没有显示输出。为什么不?我必须使用系统调用。如果行打印后很简单,我如何在数字后面添加空格?

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {

int n, i = 0;
char buf[1];
int reader=0;

if(argc > 1){
reader = open(argv[2],O_RDONLY);
}

while(n = read(reader,buf,sizeof(buf)) > 0) {
if (buf[0] == '\n') {
i++;
write(1, &i,sizeof(i));
}
write(1,buf,sizeof(buf));
}
close(reader);
return 1;
}

最佳答案

这是该程序的一个可以正常运行的版本

注意行开头的“行号”的正确时机,包括第一行,最后一行之后没有额外的行号输出

注意高级 I/O 的使用,而不是低级 read()write()

注意检查是否缺少命令行参数

注意命令行参数缺失时对stderr的使用语句

注意当 fopen() 失败时,错误检查和向 stderr 发送正确的错误消息

请注意,每个缩进级别都是一致的,并且宽度为 4 个空格

请注意使用变量“priorCh”来跟踪何时需要输出行号。

注意 main() 参数 argcargv[] 的正确引用

#include <stdio.h>   // printf(), fopen(), fclose(), fgetc(), putc(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE





int main(int argc, char *argv[])
{

int i = 0; // line counter
int ch;
int priorCh = '\0';

FILE* reader= NULL; // init to an invalid value

if( 1 == argc )
{
fprintf( stderr, "USAGE: %s <inputFileName> \n", argv[0] );
exit( EXIT_FAILURE );
}

// implied else, correct number of command line parameters


reader = fopen(argv[1], "r");
if( NULL == reader )
{
perror( "fopen for input file failed" );
exit( EXIT_FAILURE );
}

// implied else, open successful

i++;
printf( "%d ", i );

while( (ch = fgetc( reader ) ) != EOF )
{
if( '\n' == priorCh )
{
i++;
printf( "%d ", i );
}
putc( ch, stdout );
priorCh = ch;
} // end while

fclose(reader);
return 1;
} // end function: main

这是使用上述文件作为输入时的输出

1 #include <stdio.h>   // printf(), fopen(), fclose(), fgetc(), putc(), perror()
2 #include <stdlib.h> // exit(), EXIT_FAILURE
3
4
5
6
7
8 int main(int argc, char *argv[])
9 {
10
11 int i = 0; // line counter
12 int ch;
13 int priorCh = '\0';
14
15 FILE* reader= NULL; // init to an invalid value
16
17 if( 1 == argc )
18 {
19 fprintf( stderr, "USAGE: %s <inputFileName> \n", argv[0] );
20 exit( EXIT_FAILURE );
21 }
22
23 // implied else, correct number of command line parameters
24
25
26 reader = fopen(argv[1], "r");
27 if( NULL == reader )
28 {
29 perror( "fopen for input file failed" );
30 exit( EXIT_FAILURE );
31 }
32
33 // implied else, open successful
34
35 i++;
36 printf( "%d ", i );
37
38 while( (ch = fgetc( reader ) ) != EOF )
39 {
40 if( '\n' == priorCh )
41 {
42 i++;
43 printf( "%d ", i );
44 }
45 putc( ch, stdout );
46 priorCh = ch;
47 } // end while
48
49 fclose(reader);
50 return 1;
51 } // end function: main

关于c - 使用 write() 读取标准输入/文件并打印行 - 不显示行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42471659/

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