Problems about yyin and yyout using in lex for lexical analysis - c

This is main function for lexical analysis.
If I use yyin for getting data from file, yyout execute and writes to file, but when I give codes from terminal yyout isn't working. How can I solve that?
int main(int argc, char *argv[])
{
extern FILE *yyin, *yyout;
char *input;
printf("flexing there\n argc=%d\n argv[0]=%s argv[1]=%s \n",argc,argv[0],argv[1]);
if(argc > 1 && strstr(argv[1],".g++") != NULL){
printf("we will read your file = %s\n",argv[1]);
yyin = fopen(argv[1], "r");
}
else if(argc > 1){
printf("your file type is wrong ,must be .g++ type\n");
return 0;
}
else{
printf("enter your code please\n ");
}
yyout = fopen("outputlex.txt", "w");
yylex();
return 0;
}
I use yyout at rule section like that
%%
"(" fprintf(yyout,"OP_OP\n");
%%

In C, when you write to a file, the output is kept in a buffer until there is enough data to make it worthwhile writing, typically around 4kb. So if you just write a few bytes, you won't see anything in the file until it is closed.
By contrast, when you write to the terminal, the output is usually only buffered until a newline character is written. And if you write to stderr, the output is always immediate.
You can change the buffering for a stream by calling setvbuf right after the fopen. You can also force the stream's buffer to be sent using fflush.

Related

Segmentation fault when not specifying input file on command line

I am writing a program that reads from a file passed as an arguement, or reads from stdin if no arguements are given.
The code runs fine with a file passed, but I get a seg fault when no file is passed.
I basically call fopen on argv[1] if a file was given, but if no file was given I call:
f = fopen("stdin", "r");
Is this the correct syntax for opening stdin as a file?
When you start a program, the main() function is not the first thing that
get's called, quite a few things happen before the main() function is
called. One of those things is to open stdin, stdout and stderr. In
general you don't need to worry about the details how the OS does that, you
just can relay that when main() is executed, these streams are open and you
can use them.
So in your case, you can do this:
#include <stdio.h>
int main(int args, char **argv) {
FILE *fp;
if(args == 1) {
fp = stdin;
} else {
fp = fopen(argv[1], "r");
if(fp == NULL) {
fprintf(stderr, "Unable to open %s for writing\n", argv[1]);
return 1;
}
}
// do your read operations on fp
if(fp != stdin) {
fclose(fp);
}
return 0;
}
So when you call the program without arguments, stdin is used, otherwise a
file is used.
The reason why your code crashes is because
f = fopen("stdin", "r");
tries to open a file literally called stdin, which you most probably don't
have. fopen will return NULL and you probably don't check for that. If you
try to use a function that expects a FILE* pointer but pass NULL, then
you'll most likely will get a segfault.
USE f = stdin;
NOT f = fopen("stdin", "r");

how to write a command line to a file in c

I'm having issues with writing this command line to a file and it's suppose to output to the screen. To me, my code looks like it should work but I'm at a complete loss (this is my first time programming in C)
Print one line describing your program
Open the first parameter as a file for writing. If no parameter is provided, write to the stdout handle
Using a loop, save the contents of the array of string pointers passed as a parameter to the main function into the file open for writing. This is usually the variable named argv.
int main(int argc, char *argv[])
{
FILE *fp;
int i;
printf("Output supplying 'multiple arguments' to this program");
fp = fopen(argv[1], "w"); //Write to file
if(fp==NULL)
{
fp = stdout;
}
for(i=0;i<argc;i++)
{
fprintf(fp, argv[i]);
}
printf("The number of arguments printed %d", argc);
return 0;
Any help provided would be greatly appreciated!
Don't ever use dynamic format strings in C. This opens you up to an extensive set of bugs, several of them security-sensitive. Instead, pass a format string that indicates your intent, like so:
for(i=0;i<argc;i++)
{
fprintf(fp, "%s\n", argv[i]);
}

How to read files in C, in this format ./filec <input.in> <output.myout>

im currently doing a project which works with input files.
The code is doing everything that i want, and its fully correct, the problem is the way im reading the file.
FILE *fp;
fp = fopen (argv[1], "r");
in the terminal im using ./filec input.in, and everything gets printed correctly in the terminal, but i have to open the file in this way:
./filec < input.in > < output.myout > and im not sure what does that entail.
Thank you, and sorry for the poor english
Your argv[1] would have the input file, and yourargv[2] would have the output file.
A basic beginning layout for you to work on would be:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (argc != 3)
{
exit(EXIT_FAILURE); //If there are not three arg, terminate the program.
}
FILE *fp_read, *fp_write;
fp_read = fopen(argv[1],"r");
fp_write = fopen(argv[2],"w");
//Do whatever you want with it.
fclose(fp_read);
fclose(fp_write);
return 0;
}
I assume you have a typo and you actually mean:
./filec < input.in > output.myout
Basically, this means you are letting the shell do all the work for you, and your code can simply read from stdin and write to stdout. You might try:
fp = argc > 1 ? fopen(argv[1], "r") : stdin;
It could be you misunderstood the --help option, the first notation you describe is, for commandline arguments, the correct one. "" is just a notation that is used, meaning that you can change the name of the parts between <>.
Anyway, if you really need to use that notation to call your program, you could make a new array containing the argv[1] without <>.
pseudo code:
char newFilename[20];
//skip first and last character (if needed, changes values to skip first two and last two chars
for(i = 1; i < argv[1].length - 2; i++){
newFilename[i - 1] = argv[1][i];
}
fp = fopen (newFilename, "r");
Note that the < and > characters are interpreted as file redirection operations, so you should do (in this case) ./youprogram "< file.in >" "< file.out >"
First, read about fopen(3) and stdio(3)
You want to read from stdin
When calling fopen you always should check for failure, e.g. (after having tested that argc>1, assuming you defined int main(int argc, char**argv) as is conventional!)
FILE *fp = fopen (argv[1], "r");
if (!fp) {perror(argv[1]); exit(EXIT_FAILURE); };
so you probably want:
FILE *fp = NULL; // I prefer always initializing variables
if (argc>1) {
fp = fopen (argv[1], "r");
if (!fp) {perror(argv[1]); exit(EXIT_FAILURE); };
}
else fp = stdin;
If you invoke your program as ./myprog < someinput.txt > someoutput.txt then everything you printf, putchar or send to stdout goes into someoutput.txt, and stdin is the someinput.txt. Generally the redirection is done externally (by the shell on POSIX systems)

C appending to file after writing

I'm testing out the basic functions to operate files with.
I try to first open/close a file to create it, and then open/close it again to append to it. Lastly, I print out what is in the file.
My code currently looks like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char mark;
/* WRITING: */
file= fopen("goodbye.c","w");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
printf("Enter data to write to .c file:");
while((mark= getchar())!=EOF)
{
putc(mark,file);
}
fclose(file);
/* APPENDING: */
file= fopen("goodbye.c","a");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
char add;
scanf("%c",add);
putc(add,file);
fclose(file);
/* READING: */
file= fopen("goodbye.c","r");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
while((mark= getc(file))!= EOF)
{
printf("%c",mark);
}
fclose(file);
}
With this, I'm not able to append to the file. When using getchar(), I type ctrl+d once finished writing in the first place. After this it goes on to printing out what I just wrote, not giving me the chance to append to the file. Does ctrl+d somehow interrupt with scanf?
And how to get the result that I was looking for?
Your code only allows you to append a single character to the file, which is a little stingy. It can also (at least in theory) lead to problems on some systems if the last line of the text file does not end with a newline, which it won't if you add something other than a newline. Maybe you need a loop to read multiple characters?
Also, since you don't stop the initial input until EOF, you need to clear the 'error' on stdin with clearerr(stdin) to allow further input to occur. This works correctly on Mac OS X 10.10.1 Yosemite; it should work the same on other Unix systems. I can't answer confidently for Windows-based code unless it is using something like Cygwin to simulate Unix, but I expect it would work in much the same way there, too, even with MSVC.
Incidentally, my compiler complains about a missing & in the call to scanf() at:
char add;
scanf("%c",add);
If your compiler doesn't complain, either turn up the warning level or get a better compiler.
This code works as I'd expect:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file;
char mark;
/* WRITING: */
file = fopen("goodbye.c", "w");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
printf("Enter data to write to .c file:");
while ((mark = getchar()) != EOF)
{
putc(mark, file);
}
fclose(file);
printf("EOF 1\n");
/* APPENDING: */
file = fopen("goodbye.c", "a");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
clearerr(stdin);
char add;
while (scanf("%c", &add) == 1)
putc(add, file);
fclose(file);
printf("EOF 2\n");
/* READING: */
file = fopen("goodbye.c", "r");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
while ((mark = getc(file)) != EOF)
{
printf("%c", mark);
}
fclose(file);
return 0;
}
The only substantive changes are adding a loop around the scanf() — though frankly it would be better to use getchar() again, like in the first input loop — fixing the call to scanf(), adding the two printf() statements that report when EOF is detected, and including clearerr(stdin); to allow input to continue.
Sample output
Code without clearerr(stdin):
Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
Code with clearerr(stdin):
Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
But it helps when you add the clearerr(stdin) to this one.
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
But it helps when you add the clearerr(stdin) to this one.

C outputting "{" when reading from file

I have written this code using Xcode to read from a file:
int main (int argc, char *argv[])
{
FILE *fp = fopen("hello.rtf", "r");
printf("%c\n", fgetc(fp));
fclose(fp);
if (fp == NULL)
{
printf("Could not open file!");
return 1;
}
// insert code here...
return 0;
}
The character that I get is "{" and it is not the first character in the file.
The RTF spec says that the first character in an RTF file should be {, so it seems that you are getting the expected result. Bear in mind that a word processing software will not show you the exact characters in the file, but it will show you the formatted text which has been described by the markup characters in the file.
To see the exact characters in the file you could output it with cat (POSIX) or type (DOS / Windows command prompt).
The if (fp == NULL) check should go immediately after the fopen line; by the end it's too late.

Resources