C - change stdin and wait for user input - c

I have the following code:
#include <stdio.h>
int main()
{
char c = 0;
fclose(stdin);
stdin = fopen("newin", "r");
if(stdin != NULLL)
{
scanf("%c", &c);
printf("%d", c);
}
else
printf("Error");
}
I want my program to wait for a change in the stdin file. I created it blank, but it returns 0.
If a put like a 'a' char in it it prints 97 like it should.
How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?

How can I make the scanf wait for a change in the file, like it was waiting for me to write in the terminal window?
You can't.
Input from stdin and a file from disk are handled differently. When you are reading from a file, the file must have everything in order before you open it to read from it.

Related

Terminate C program which stdin is linked to output of other program

I have a program x, which I want to cleanly terminate.
You can run it by simply doing ./x and use the terminal to write lines to stdin directly and terminate it by writing exit.
However, if you use: cat file.txt | ./x, the stdin is now piped from the file and therefore you can never type exit.
The best way to end this program would be for it to automatically terminate once the last line was read from the file.
Alternatively, I'd like to re-route stdin back to the terminal if that is at all possible, to further allow manual input as before.
Here is some sample code:
int main() {
// ...
while (ongoing) {
size_t n = 0;
char* ln = NULL;
getline(&ln, &n, stdin);
strtok(ln, "\n");
strtok(ln, "\r");
if (strcmp("exit", ln) == 0) {
break;
}
//...
}
}
you're using getline to read your input. getline returns -1 on EOF. This makes it easy.
if (-1==getline(...))
break;
When you have read all the input from a pipe, EOF will be raised up to indicate that the full input has been reached.
In your example, this will be rougly equivalent with exit, so you can also check the return value of getline to see if the EOF has reached (in which case -1 will be returned).

why is fprintf() not writing to a file?

I am trying to get some text entered from the console written into a file called "output.txt" with the following code..
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("write something\n");
char c;
FILE *output=fopen("output.txt","w");
if(!output)
{
printf("couldn't open file\n");
return 1;
}
while(c=getchar())
fprintf(output,"%c",c);
fclose(output);
}
but the "output.txt" file contains no text when i open it. Why is this happening?
All help is highly appreciated .
Since you do not have a proper exit condition in your loop, the only way to terminate your program is by forcefully ending the process. This means that there is no guarantee that any pending buffered output will be written to the stream output.
What you can do is change your loop condition to while((c = getchar()) != EOF). Then, you can use the characters Ctrl+Z (Windows) or Ctrl+D (*nix) to make the loop condition false, reaching the line fclose(output), which will flush the buffer and close the file.
Also, make c an int, since that's what EOF is.
You probably want something like this:
...
while ((c = getchar()) != 'X')
fprintf(output, "%c", c);
fclose(output);
...
Input:
ABCXEnter
Output.txt will contain ABC.

Read each line in a text file when I press a key? C programming

I know how to use fgets inside a while loop to read an entire text file, but how can I press a key inside that loop, so it will read another line, one at a time?
I tried with a simple printf("Press any key\n") getchar() but nothing happens, I run the programm and it just doesn't do anything, not even show the first line. I'm assuming this may be a stupid question but I can't find how to do this :(
Here is what I've tried:
/* gcc readline.c -Wall -o read */
#include <stdio.h>
//#include <stdlib.h>
int main (int argc, char *argv[]) {
char url[]="dbus.log";
FILE *arq;
char info[1000];
arq = fopen(url, "r");
while (fgets(info, sizeof(info), arq) != NULL) {
printf("%s", info);
printf("Press Any Key to Continue\n");
getchar();
}
fclose(arq);
return 0;
}
The program isn't showing the prompts because stdio is buffered and you're not flushing. Use fflush(stdout); to ensure that buffered output is produced.
Like this:
fflush(stdout);
getchar();
Also note that by default stdin is in "cooked" IO mode. Pressing enter will produce a character, but other characters will be buffered until enter is pressed.

Read file without fopen() (C language)

I am working on a school project in which we have to do some operations (select, min, max) on a table saved in .txt file.
The problem is that we can't use common functions such as fopen, fscanf, fclose.
The program will be launched from command line like this: .\project.exe select parameters <table.txt
Do you have some ideas how to get content of the .txt file to stdin without using fopen?
Thanks.
You do not need to open the file - the operating environment will do it for you.
When your program is called with <table.txt, your standard input is switched to read from that file instead of the keyboard. You can use scanf to read the data, and do not worry about opening and closing the file.
Same goes for the output of your program and the >table_out.txt redirection: rather than printing to the screen, printfs in your program would be writing to a file, which would be automatically closed upon your program's exit. Of course if you need to print something to the screen when your output is redirected, you can do so by printing to stderr (e.g. fprintf(stderr, "Invalid table format\n").
There are few ways to acomplish this.
Reading STDIN
I guess the teacher wants this method in particular. The idea is reading standard input rather than particular file.
In C++ you can simply read the stdin object. Here's an example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, 10, stdin);
/* remove newline, if present */
i = strlen(str)-1;
if( str[ i ] == '\n')
str[i] = '\0';
printf("This is your string: %s", str);
return 0;
}
Source: http://www.java2s.com/Code/C/Console/Usefgetstoreadstringfromstandardinput.htm
Using system utils
You can call "type" util # Windows (not sure about it) or "cat" util in Linux as a subprocess to read some partticular file. But this is rather a "hack", so I do not recommend using this one.

understanding fputc

I am trying to get a basic understanding on how to use fputc in C. I have read some documentation that is out there and believed I had it right. But every time I try to use the script I wrote by executing ./fputc > test.txt where text.txt is a text file with one line of text.
This is my script:
int
main(int argc, char **argv){
int ch;
FILE *input;
input = fopen("text.txt", "w+");
while ((ch = getchar()) != EOF){
fputc(ch, input);
}
fclose(input);
return 0;
}
I get no errors on compilation and for some reason the script does not reach EOF at the end of the text file. Shouldn't the getchar return EOF when it reached the end of the text file?
The text (text.txt) file does not appear to be edited, although it is created. So somewhere in my while loop something is going wrong.
I am new to C programming (if you couldn't tell) and this little script has me befuddled.
Any help would be appreciated, or any links to sites with further detail would also be great.
Cheers,
S.
What you in essence say is:
Console: Run my_program and write anything it outputs to test.txt.
Program: Open text.txt and write any input to stdin to that file.
Your console normally have three standard streams stdin, stdout and stderr. These streams you can redirect. If you are on Windows also look at i.e. redirection.
When you say ./my_prog > test.txt, what you tell your console, (not my_prog), is to write anything my_prog writes to stdout to the file test.txt.
If you in your code say i.e. printf("Hello");, then Hello would be written to the file test.txt.
If you had turned your redirection around by saying ./my_prog < test.txt instead, would be; stream the file test.txt to my_prog. Which, in turn, if there was any text in test.txt would result in a copy of test.txt to text.txt.
Now in your code you say:
int main(void)
{
int ch;
FILE *input;
/* Here you open a handle to the file text.txt for reading and writing */
input = fopen("text.txt", "w+");
while ((ch = getchar()) != EOF) { /* get next char from stdin */
fputc(ch, input); /* write that char to the handle input */
}
fclose(input); /* close the handle */
return 0;
}
So what happens, the way you run it, is:
In your code:
Open text.txt
Wait for input (data entered to stdin) - typically user entering text to console, passed to program when Enter is pressed.
In console:
Redirect anything from my_prog to test.txt.
You say:
the script does not reach EOF
Well, as it reads from stdin it will only (not without exception) get EOF under two conditions.
If you redirect a file to your program. I.e. ./my_prog < foo.txt (notice <, not >).
- What would happen then is that my_prog would read the data from the file foo.txt and when that file ends your program would receive a EOF. And, hence quit.
If you manually enter EOF to stdin.
- On Linux and OSX Ctrl-D, on Windows Ctrl-Z
Now, if you test this by typing text to console remember that write actions like fputc()is buffered. What this mean is that the data is not written to the file right away, but only when a given amount of data is in buffer, fflush() is called, stream is closed, you turn off buffering, etc.
Also; if you run your program. Enter text, enter some more text, and then hit Ctrl-C to abort the program it is a big chance you end with no data in your text.txt.
The reason for this is that the program is killed and thereby fclose() never called, and hence no flush to file.
On your further endeavors in programming it would be a very good idea to make a habit of not presuming anything. I.e. do not presume fopen() is OK.
FILE *fh;
char *outfile = "foo.txt";
if ((fh = fopen(outfile, "w")) == NULL) {
fprintf(stderr,
"Unable to open file %s\n --",
outfile);
perror(" fopen() ");
return 1;
}
Most functions has a way to check if operation was a success. I.e:
if (fputc(ch, fh) != ch) { err ...
This will make your code a lot safer, give you hints on where it fails etc.
Some links:
Look at redirection links at top of post.
Look at the functions in stdio.h (good overview), stdio.h (examples etc.). I.e.:
stdin
stdout
stderr
fopen()
fflush()
setvbuf()
setbuf()
...
getchar returns the next character from the standard input (stdin).
It is equivalent to getc with stdin as its argument.
Hence, your code reads from standard input instead of FILE* input.
Use fgetc here.
fgetc returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character.
So, Use fgetc to read from a file:
while ((ch = fgetc(input)) != EOF)
your program and the shell are both writing the same file. you should remove the output redirection > test.txt from your command line

Resources