Delete character "\n" from string with read - printf

I've to do a project but I hit a issue.
I receive a string from a read but when I would see what data are in my buffer, it shows an "\n" at the end of the file. However I don't need it to use after to deal with a argument in my function.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
char buf[100];
read(1, buf, sizeof(buf));
printf("%s", &buf);
// If I write: "/tmp/", printf shows: "/tmp/\n"
DIR* drp = opendir(buf);
// Logically: no such file or directory
}
Thanks

The problem in how you read string from stdin. read function waits until you enter a newline or other EOF key. But it includes this last symbol in the result.
1) I think you better use scanf.
scanf("%s", buf);
2) Or you need to take care of the last symbol by yourself.
char buf[100];
char res[100];
int n = read(1, buf, sizeof(buf));
if(n > 0) {
memcpy(res, buf, n - 1);
} else {
printf("Error while reading\n");
}

Related

eclipse error in c/c++ project in run time.output is printed in first will be blank. we enterd

#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a1=20,b1=40,temp;
temp=a1;
a1=b1;
b1=temp;
printf("a1: %d, b1: %d",a1,b1);
return EXIT_SUCCESS;
OUTPUT
2
4
5
enter three numbersresult is 3.666667
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setbuf(stdout,NULL);
float num1,num2,num3,average;
printf("enter three numbers");
scanf("%f%f%f",&num1,&num2,&num3);
average=(num1+num2+num3)/3;
return EXIT_SUCCESS;
}

Simple Regex pattern unmatched with Flex/Bison (Lex/Yacc)

I have built a trivial compiler using Flex and Bison which is supposed to recognize a simple string in a source file and I use the standard error stream to output a message if the string is recognized correctly.
Below is my code and my unexpected result.
This is the source file (testsource.txt) with the string I try to recognize:
\end{document}
This is the Flex file (UnicTextLang.l):
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "y.tab.h"
void yyerror(char *);
int yylex(void);
/* "Connect" with the output file */
extern FILE *yyout;
extern int yyparse();
%}
%%
^\\end\{document\}$ { yyerror("end matched"); return END; }
/* skip whitespace */
[ \t] ;
/* anything else is an error */
. yyerror("invalid character");
%%
int main(int argc, char *argv[]) {
if ( argc < 3 )
yyerror("You need 2 args: inputFileName outputFileName");
else {
yyin = fopen(argv[1], "r");
yyout = fopen(argv[2], "w");
yyparse();
fclose(yyin);
fclose(yyout);
}
return 0;
}
This is the Bison file (UnicTextLang.y):
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "y.tab.h"
void yyerror(char *);
int yylex(void);
/* "Connect" with the output file */
extern FILE *yyout;
%}
%token END
%%
document:
END
|
;
%%
int yywrap(void) {
return 1;
}
void yyerror(char *s) {
fprintf(stderr, "%s\n", s); /* Prints to the standard error stream */
}
I run the following commands:
flex UnicTextLang.l
bison -dl -o y.tab.c UnicTextLang.y
gcc lex.yy.c y.tab.c -o UnicTextLang
UnicTextLang.exe testsource.txt output.txt
What I expect to see printed in the console is
end matched
But this is what I get:
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
invalid character
What’s wrong?
This issue is caused by the end-of-line code for a Windows machine being two characters (\r\n) when on other systems it is one (\n).
This is explained in the flex manual:
‘r$’
an ‘r’, but only at the end of a line (i.e., just before a newline). Equivalent to ‘r/\n’.
Note that flex’s notion of “newline” is exactly whatever the C compiler used to compile flex interprets ‘\n’ as; in particular, on some DOS systems you must either filter out ‘\r’s in the input yourself, or explicitly use ‘r/\r\n’ for ‘r$’.
The quick solution is to change:
^\\end\{document\}$
to
^\\end\{document\}\r\n
However, if your expression is at the end-of-file without an end-of-line, which is possible in Windows, then you would have to specifically match that case also. Flex does permit the matching of end-of-file with:
<<EOF>>
but this will cause all kinds of other side effects and it is often easier not to anchor the pattern to the end (of line or file).

Run busybox netcat in background script?

Note, I have looked at Using netcat/cat in a background shell script (How to avoid Stopped (tty input)? ), but it doesn't seem to apply to my case. I'm using the netcat (nc) that comes with busybox, and none of the workarounds I've found seem to work for me. Also, there is no -d option, nor are there any -q options.
I'm trying to use netcat to receive a file in a shell script, and this script is in a background process that apparently doesn't have a stdin. I have tried several different approaches, but none seem to work. Here's what I've tried:
nc -l -p 8888 > file returns the instant the remote sender connects, dropping the connection early.
nc -l -p 8888 < /dev/null > file does the same.
echo -n | nc -l -p 8888 > file does the same.
tail -f /dev/null | nc -l -p 8888 > file will receive the file, but it doesn't quit when the file transfer is finished.
I'm running out of ideas. Is this version of netcat fundamentally broken?
Well, it's been days, and nobody had an answer, so I had to roll my own. Below is the code, in case it's useful to anyone.
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/uio.h>
#include <unistd.h>
void bail(const char *s)
{
perror(s);
exit(-1);
}
int listen_socket;
struct sockaddr_in my_addr;
void setup_socket(int port)
{
int er;
listen_socket = socket(AF_INET, SOCK_STREAM, 0);
if (listen_socket < 0) bail("socket");
int on=1;
er = setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (er < 0) bail("setsockopt");
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
er = bind(listen_socket, (struct sockaddr *)&my_addr,
(socklen_t)sizeof(struct sockaddr_in));
if (er < 0) bail("bind");
er = listen(listen_socket, 1);
if (er < 0) bail("listen");
}
int listen_wait()
{
socklen_t len = sizeof(struct sockaddr_in);
int s = accept(listen_socket, (struct sockaddr *)&my_addr, &len);
if (s < 0) bail("accept");
return s;
}
char buf[1024];
int main(int argc, char *argv[])
{
int port = 8888;
int sock;
int tryagain;
if (argc>1) {
port = atoi(argv[1]);
}
setup_socket(port);
sock = listen_wait();
do {
int i = read(sock, buf, 1024);
tryagain = (errno==EAGAIN);
if ((i<1) && (!tryagain)) {
shutdown(sock, 2);
close(sock);
return 0;
}
if (i>0) {
fwrite(buf, 1, i, stdout);
}
} while (1);
return 0;
}
This will do the trick
sleep 99999 | nc -l -p 8888 > file

Bison/Flex Parsing File

I have recently tried using GNU Bison and Flex to write a interpreter. The text I want the interpreter to recognize is print "Hello" and I have tried the following:
flex file:
%{
#include <iostream>
using namespace std;
#define YY_DECL extern "C" int yylex()
#include "gbison.tab.h"
%}
%%
[ \t\n] ;
'\"' return QUOTE;
[a-zA-Z0-9]+ { yylval.sval = strdup(yytext); return STRING; }
%%
bison file:
%{
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
extern "C" int yylex();
extern "C" int yyparse();
extern "C" FILE* yyin;
void yyerror (const char* s);
%}
%union {
char* sval;
}
%token <sval> STRING
%token QUOTE
%%
str:
STRING QUOTE STRING QUOTE
{
if (strcmp($1, "print") == 0)
{
cout << $3 << flush;
}
if (strcmp($1, "println") == 0)
{
cout << $3 << endl;
}
}
;
%%
main(int argc, char* argv[])
{
FILE* input = fopen(argv[1], "r");
if (!input)
{
cout << "Bad input. Nonexistant file" << endl;
return -1;
}
yyin = input;
do
{
yyparse();
} while (!feof(yyin));
}
void yyerror(const char* s)
{
cout << "Error. " << s << endl;
exit(-1);
}
But when I pass print "hello" to the compiled program I get:
"Error. syntax error
I think that the issue is the STRING QUOTE STRING QUOTE but I am not sure. What is exactly is going wrong? How would I get the interpreter to print hello?
The answers are below, but I hope the following is more generally useful, as fishing instruction.
There are a variety of debugging tools which would help you. In particular, flex provides the -d flag:
-d, --debug
makes the generated scanner run in "debug" mode. Whenever a pattern is recognized and the global variable yy_flex_debug is non-zero (which is the default), the scanner will write to stderr a line… (flex manual)
bison also provides a debug facility. (bison manual)
There are several means to enable compilation of trace facilities:
the macro YYDEBUG…
the option -t (POSIX Yacc compliant)…
the option --debug (Bison extension)…
the directive %debug…
We suggest that you always enable the debug option so that debugging
is always possible.
…
Once you have compiled the program with trace facilities, the way to
request a trace is to store a nonzero value in the variable yydebug.
You can do this by making the C code do it (in main, perhaps), or you
can alter the value with a C debugger.
Also, remember that flex inserts an automatic rule which causes any otherwise unrecognized character to be echoed to the output. ("By default, any text not matched by a flex scanner is copied to the output" -- Some simple examples) That's why you have the extra " in the error message being printed by your program:
"Error. syntax error
^
That's a bit subtle, though. Tracing flex would have shown you that more directly.
So, finally, the problem(s):
The flex pattern '\"' does not match a ". It matches '"', because single quotes are not special to flex. That's definitely why your parse fails.
Fixing that will let your program parse a single command, but it will generate a syntax error if you try to give it two print commands in the same input. That's because bison always parses until it receives an END token from the lexer, and the lexer (by default) only provides an END token when it reaches the end of the input. You can change
the lexer behaviour (by sending END in other circumstances, for example a new-line) (not recommended)
the parser behaviour (by using ACCEPT) (possible, but rarely necessary)
the grammar, so that it recognizes any number of statements. (recommended)

why calles function yyerror() in sample programm

curs.l :
%{
#include <stdlib.h>
#include "tree.c"
#include "yycurs.h"
%}
L [a-zA-Z_]
D [0-9]
D4 [0-3]
IDENTIFIER ({L})({L}|{D})*
INT4 {D4}+'q'
INT {D}+
%%
{IDENTIFIER} {return VARIABLE;}
%%
int yywrap(void){
return 0;
}
curs.y:
%{
#include stdio.h
void yyerror(char*);
int yylex(void);
%}
%token VARIABLE INTEGER
%%
var: VARIABLE {printf($1);};
%%
void yyerror(char *s){
fprintf(stderr, "11\n");
fprintf(stderr, "%s\n", s);
}
int main(void){
yyparse();
return 0;
}
when i run my compiled progrum, i have such result:
./curs
ff //I introduced
//result
ff //I introduced
11 //result
syntax error //result
evgeniy#evgeniy-desktop:~/documents/compilers$
Can anybody explain me, why there appears 'syntax error'?
Thanks in advance.
Your grammar defiles that a valid file consists of exactly one VARIABLE. To have more then one, you need to introduce a recursive rule.
%start vars
%%
var: VARIABLE {printf($1);};
vars: var
| vars var;
%%