Reputation: 269
I have this code 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);
}
Functions used in the code:
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';
}
I have 2 pipes one for input and other for output. I write on input pipe , using echo "4\n2\n" > i
(by terminal) the string "4\n2\n"
and by two readline( the 2 if in the while cycle) I should read the "4" and then by second readline the "2". This because the Readline
function splits by '\n'; but when end first if in the while cycle prints var1
(should contain only "4"
) , but it prints 4\n2\n
and I don't understand why.
What do I wrong?
Upvotes: 1
Views: 469
Reputation: 90521
\n
is not actually a newline character. It's an escape sequence which, in some circumstances, is interpreted and causes the interpreter to substitute a newline character. The C compiler does this interpretation and substitution in string and character literals, so your compiled program actually contains the newline character.
The shell and its echo
built-in command do not necessarily do this interpretation. The bash
that ships with OS X does not interpret such escape sequences by default. You can make it do that by passing the -e
option. Note that /bin/echo
or the built-in echo
commands of other shells may not support that option.
So, you throught you were providing the input character stream 4
, newline, 2
, newline, newline to your program. What you were actually providing was 4
, \
, n
, 2
, \
, n
, newline.
Upvotes: 1