$ ./main < input
If I were to check for new lines in python, I would open the file and then analyze the lines, but this almost seems like magic.
int main(){
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
nl++;
printf("%d\n", nl);
return 0;
}
How does it know to accept any input file without being stated within the code?
The < symbol in the shell is an input redirection. It states that the contents of the given file input in this case, will be read as stdin.
So any function such as getchar that reads from stdin will actually be reading from the file input in this case.
A similar program in Python would also use functions that read from stdin instead of from a file.
Related
This is the code:
#include<stdio.h>
main(){
int c;
c = getchar();
while( c != EOF ){
putchar(c);
}
}
I have made another file named "AFile" using vim.
To display the contents of "AFile" using my program, what command do I write in the terminal?
Your program reads from STDIN (fd 0), so you need to provide data at via stdin. In most shells, this can be done with the redirect operator <:
./yourprogram < inputfile
Another way would be using a pipe, but it is generally not recommended, because it needs to start an unnecessary second process:
cat inputfile | ./yourprogram
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.
I am currently working through K&R for C. In section 1.5, we basically create a program for word count. The code is as follows,
#include <stdio.h>
#define IN 1
#define OUT 0
int main()
{
int c;
long int nl, nc, nw;
int state;
nl = nw = nc = 0;
state = OUT;
while((c = getchar())!= EOF){
++nc;
if (c == '\n'){
++nl;
}
if (c == ' '||c == '\n'|| c == '\t'){
state = OUT;
} else if (state == OUT){
state = IN;
++nw;
}
}
printf("\n%ld %ld %ld\n", nl, nc, nw);
}
When I compile this program with gcc and open the executable and type something such as
Hello
World
I get output
1 11 2
Which makes sense as we have 1 '\n' newline characters, 11 characters (including newline), and 2 word. What is interesting is when I do
vim hello.txt
and type
Hello
World
and then issue the command
cat hello.txt|./a.out
I get the following output
2 12 2
Why are the outputs from this different from before because all I am doing is streaming the file into the executable so I do not understand what is different. Please do explain.
Thank You.
Not your program's feature, but Vim's. See: What does the noeol indicator at the bottom of a vim edit session mean?
Vim automatically appends a newline at the end of file if there isn't when saving.
Type
:set noeol
in Vim and save the file again, then your program will output 11 as the second number.
P.S. It's redundant to use cat something | program, just program < something is enough.
After you type the charactors into the file and save it, at the end of the file, a 0x0a is added to the end of the file automaticly
I have a C console application under Linux (Raspbian - Raspberry Pi). The program has some character animation - it prints out messages character by character. For example, the text
Please give me your name!
is printed out completely after 5 seconds (char by char).
Afterwards, the user is asked to type in their name, which works just fine if the user waits for the message to be printed out. However, if the user is impatient and hits the keys on the keyboard randomly, the input request later is compromised.
Imagine the user types in
abc\nefgh\n
while the above text is being echoed ('\n' means new line - enter). If that happens, the user will not be asked to properly type in his/her name, but the array of characters 'abc' will be accepted as input and gets validated.
My question is how to disable input (buffering) temorarily (on Linux). I have tried several methods and read numerous posts about doing so, but none of them worked for my purpose.
The function that is responsible for asking for input is as follows:
int getLine(char *s, int length)
{
int i;
char c;
for (i = 0; i < length && (c = getchar()) != EOF && c != '\n'; i++)
{
if (c == '\0')
{
i--;
}
else
{
s[i] = c;
}
}
s[i] = '\0';
while (c != EOF && c != '\n')
{
c = getchar();
}
return i;
}
Empty lines are eliminated with the help of a while loop in the function calling the one above so enter inputs are considered invalid.
I tried closing stdin, but could not reopen it:
fclose(stdin);
and emptying buffer before the getLine:
char buf[BUFSIZ];
while (c = fgets(buf, BUFSIZ, stdin) != NULL);
Unfortunately, it did not work as it does with text files.
fflush(stdin); did not work either and is not pretty anyway.
My goal is to prevent users from typing in anything while the text is being written out and to ignore/close input buffering (stdin) temporarily. Also, it would be great to disable outputting (flushing) user inputs during printing as it gets displayed on Linux terminal.
You may do this by interacting with TTY directly. Look into source code of passwd or similar utilities for inspiration.
Function below clears TTY input buffer (error handling omitted). You need to call it just before reading user input.
#include <sys/ioctl.h>
#include <termios.h>
void clear_user_input() {
if (isatty(STDIN_FILENO)) {
int fd = open(ttyname(STDIN_FILENO), O_RDONLY);
ioctl(fd, TCFLSH, TCIFLUSH);
close(fd);
}
}
This question already has answers here:
End of File (EOF) in C
(3 answers)
Closed 7 years ago.
When I use this code, I can type into the command line and get back what I typed:
main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
}
Output:
~/code/c $ ./a.out
one
one
two
two
But when I use this code, it only works when I pipe in data, not when I type data into the command line:
main() {
int nc;
nc = 0;
while (getchar() != EOF) {
nc++;
}
printf("%d\n", nc);
}
When I pipe data in from a text file:
~/code/c $ ./a.out < practice.txt
14
When I try to input data from the command line:
~/code/c $ ./a.out
one
two
three
What's going on?
The while loop never exits since while (getchar() != EOF) is always true. After you're done with the input, press Cntrl+D for Linux or Ctrl+Z for Windows to indicate EOF.
Like everyone mention, you program doesn't stop. The while loop needs a condition to stop. you have to either use CTRL+Z (Win) or CTRL+D(Unix) to stop it, When you pipe it actually sends that character for you. Because EOF is END_OF_FILE. So when you hit the end of your file. the OS sends that character for you.