gpt4 book ai didi

c - 阅读命名管道问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:19 25 4
gpt4 key购买 nike

我有这个代码 C:

#define BUFSIZE 256

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


if( argc != 3)
{
perror("Erro argument");
exit(1);
}

if( (fdIn = open(argv[1], O_RDONLY ) )<0)
{
perror("Errr pipe input");
exit(1);
}

if( (fdOut = open(argv[2], O_WRONLY ) )<0)
{
perror("Errr pipe output");
exit(1);
}

int c = 2;
while(c--)
{
char var1[BUFSIZE];
char var2[BUFSIZE];
char string[100];

memset(var1, 0, sizeof(var1));
memset(var2, 0, sizeof(var2));
memset(string, 0, sizeof(string));


if( readLine(fdIn, var1, sizeof(var1)) == 0)
{
printf("exit1\n");
exit(0);
}
printf("%s\n",var1);
if( readLine(fdIn, var2, sizeof(var2)) == 0)
{
printf("exit2\n");
exit(0);
}

removeNewLine(var1);
removeNewLine(var2);

if( atoi(var2) != 0){
if( atoi(var1) == 0 || (atoi(var1) % atoi(var2)) == 0 )
sprintf(string,"ok\n");
else
sprintf(string,"no\n");

}

printf("%s", string);
writeLine(fdOut, string, strlen(string));
}
close(fdOut);
close(fdIn);
exit(0);

}

代码中使用的函数:

int readLine( int fd, char* str, int bufferSize)
{
return readToDel(fd, '\n', str, bufferSize);
}

int readToDel( int fd, char delimiter, char* str, int bufferSize)
{
int n;
int byteLetti =0;
int index=0;

do /* Read characters until NULL or end-of-input */
{

if( (n = read (fd, str+index, 1)) < 0)
{
perror("Errore: lettura dal file descriptor fallita\n");
exit(1);
}
byteLetti+=n;


}
while (n > 0 && *(str+index++) != delimiter && index < bufferSize);


return byteLetti; /* Return false if end-of-input */
}
void removeNewLine( char *s )
{
removeDel(s, "\r\n");
}
void removeDel( char *s, char *del)
{
s[strcspn ( s, del )] = '\0';
}

我有 2 个管道,一个用于输入,另一个用于输出。我在输入管道上写,使用 echo "4\n2\n"> i (通过终端)字符串 "4\n2\n" 和两个 readline( 2 如果在 while 循环中)我应该阅读“4”,然后在第二行阅读“2”。这是因为 Readline 函数被 '\n' 分割;但是如果在 while 循环中首先结束时打印 var1 (should contain only "4" ) ,但它会打印 4\n2\n 和我不明白为什么。我做错了什么?

最佳答案

\n 实际上不是换行符。这是一个转义序列,在某些情况下,它被解释并导致解释器替换换行符。 C 编译器在字符串和字 rune 字中进行这种解释和替换,因此您编译的程序实际上包含换行符。

shell 及其 echo 内置命令不一定执行此解释。默认情况下,OS X 附带的 bash 不解释此类转义序列。您可以通过传递 -e 选项让它做到这一点。请注意,/bin/echo 或其他 shell 的内置 echo 命令可能不支持该选项。

所以,您一直在为您的程序提供输入字符流 4, newline, 2, newline, newline。您实际提供的是 4\n2\ , n, 换行符。

关于c - 阅读命名管道问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458747/

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