Stdin doesn't work when I run the program - c

I have the following C code in code.c
int main(int argc, char *argv[]) {
FILE *openFile = NULL;
openFile=stdin;
}
but when I compile and run my code with
gcc -g -o compiledcode code.c
./compiledcode
the terminal doesn't prompt me for an input. What is wrong?

You just open stdin as file but you don't read your file.
There are many different ways to get input from stdin.
Function getchar can be used to read a single character from stdin. Use getc() or fgetc() to read from an arbitrary file stream.
Example:
int c = getchar();
printf("you entered %c\n", c);
Function fgets can be used to read a line from file.
Example:
char data[200];
fgets(data, sizeof(data), stdin); // we type stdin as file.
printf("you entered %s\n", data);
Function scanf and its family of functions can be used to read many different formats from stdin.
example:
char data[200]; // size need be bigger or equal to input length
scanf("%199s", data); // Protect from buffer overflow
printf("you entered %s\n", data);

Related

How to get the output of another program as pipe to my program?

For e.g i have the following program in windows.
#include <stdio.h>
int main(int argc, char *argv[]) {
char *input = argv[1];
printf("your input: %s", input);
return 0;
}
When i run a cmd shell and invoke
C:\>whoami | main.exe
i get as output
your input: (null)
The first argument argv[0] (the filename itself) is passed correct. How to receive the output of whoami as input to my program?
Edit: Since people mostly ask for code if you ask a question, i will also provide code in my answer. Just to be fair. The solution i use (thanks to Gerardo Zinno) is to read from stdin - so i use scanf.
char input[1024] = {0};
read(STDIN_FILENO, input, 1024);
input[strcspn(input, "\n")] = '\0';
printf("you wrote: %s", input);
return 0;
You have to read from the stdin just like if the input was coming from a user typing in the terminal. The pipe will send (link) the stdout of whoami to the stdin of your program.
There are many options to read from the stdin. You can use fread with stdin as last parameter, scanf, fscanf(stdin,...),...

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.

How to write and read more than one word in C string

I'm doing program and in this program i have two processes, server and client. Server have to read string from input and then write into FIFO file. Client have to read strings from FIFO file and then wrote into .txt file.
This are only function responsible for server and client. File FIFO and fork'ing is doing in main function.
void server(void)
{
FILE *fp1, *fp2;
char string[100];
while(1)
{
fp1 = fopen("FIFO1", "w");
fprintf(stdout, "Type string: ");
scanf("%s", string);
fputs(string, fp1);
fclose(fp1);
sleep(1);
}
}
void client(void)
{
FILE *fp,*fp1;
char string[100];
while(1)
{
fp = fopen("FIFO1", "r");
fgets(string, 100, fp);
fclose(fp);
fp1 = fopen("file.txt", "a");
fprintf(fp1,"%d_file: I get: %s\n", getpid(), string);
fclose(fp1);
}
}
And my problem is when i type a string like "stack overflow", when i have two word, in my file.txt i get to lines:
8965_file: I get: stack
8965_file: I get: overflow
Is there any way to write this in one line ? Like this:
8965_file: I get: stack overflow
It's because of scanf() which stops reading when a white space occurs for the "%s" specifier, change it to "%99[^\n]" or use fgets() instead but keep in mind that fgets() will read the '\n' and fputs() will add one so you might end up with more lines than you want.
Hint: For an array use fgets(string, sizeof(string), fp); to make your code easier to maintain.
You can use gets(string) to get more than one word instead of using scanf().
Reference Link : www.keizerkong.com/c/c_string.html

junk characters from stdin after reading from file in C

After succesfully reading a re-directed file to my program from the console, I ask a user to enter a word, then use scanf() to read in the word.
The problem i'm having is that scanf() is immediately reading in junk characters and then the program continues. It doesn't even pause to let the user enter anything in the console. It doesn't happen when I don't open a file. EVERYTHING else works perfectly. What could be the issue:
**I tried everything suggested, still can't get it to work. I've made a new project that is just for getting this part to work, here it is. Ignore that scanf is only looking for a single character, even though I ask for a word. I did this just to see if the program would actually pause and allow me to enter something, but it doesn't. Just enters some garbage and program ends.
main(){
int n,i;
char ch;
char line[80];
while(fgets(line, 80, stdin) != NULL){
for(i=0;i<80;i++){
ch=line[i];
if(ch=='\n'){
printf("%c",ch);
break;
}
else{
printf("%c",ch);
}
}
}
printf("Please enter a word: ");
scanf("%c",&ch);
}
You can't re-direct stdin from a file and then also use the keyboard for input (that I know of). If you want to do that, it's simpler to have the program take the input file as a command-line argument and then run it like so: prog myfile.txt. Also, leave yourself a pad with fgets() -- use one less than the allocated array for maxlen. It's always safest with C char arrays to use one less than the allocated length for anything requiring a maximum length in case the maximum length is not including the '\0' terminating character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
FILE *f;
int i;
char line[80];
if (argc<2)
{
printf("Usage: %s <inputfile>\n",argv[0]);
exit(10);
}
/* Open file and echo to stdout */
f=fopen(argv[1],"r");
if (f==NULL)
{
printf("Cannot open file %s for input.\n",argv[1]);
exit(20);
}
while (fgets(line, 79, f) != NULL)
printf("%s",line);
fclose(f);
/* Get user input from stdin */
printf("Please enter a word: ");
if (fgets(line,79,stdin)==NULL)
{
printf("Nothing entered. Program aborted.\n");
exit(30);
}
/* Remove CR/LF from end of line */
for (i=strlen(line)-1;i>=0 && (line[i]=='\n' || line[i]=='\r');i--)
;
line[i+1]='\0';
printf("The word entered is: '%s'\n",line);
return(0);
}
sscanf is used to input from a stream or a buffer, and in unix stdin is considered as file so u are supposed to use fscanf which inputs from a file so use fscanf(stdin,"%s",testword);

Something wrong while using crypt function in C

I am using the crypt function in C, where I am giving the command line input an encrypted word. I use the words in /usr/share/dict/words and encrypt them using the crypt function and then compare the encrypted output of the crypt function with the command line input. If the words are the same, then I give out the non-encrypted code as the output using a printf statement.
The code is given below.
#include<stdio.h>
#define _XOPEN_SOURCE
#include<unistd.h>
#include<cs50.h>
#include<string.h>
int
main(int argc, string argv[]){
char line[80];
string crypto;
if(argc>2||argc<2)
{
printf("ERROR. Enter only one crypt");
return 1;
}
string crypti=argv[1];
FILE *fr;
string as;
fr=fopen("/usr/share/dict/words","r");
if(!fr)
{
printf("File can't be read");
exit(-1);
}
while(fgets(line,80,fr)!=NULL)
{
as=crypt(line,"50");
if(strcmp(as,crypti)==0)
{
printf("%s",line);
break;
}
}
fclose(fr);
}
The code seems to work fine just for 1 input i.e when I give "./a.out 50q.zrL5e0Sak"(without quotes). However, if I use any other input for the crypt, the code seems to fail. Another example for password:encrypted password is abaca:50TZxhJSbeG1I. The word abaca is present in the list but fails to identify. I am not able to fix this code to work for all inputs.
Add the following snippet to the beginning of while (fgets...) body:
size_t len = strlen(line);
if (len)
line[len-1]='\0';
There is usually a newline \n (when it was read) in the end of the buffer read by fgets.
Your original code works with "password" because only 8 first characters of the key are actually used by crypt. It would work with any word of length 8 or more as well.
Also, make sure that the output is flushed after you print the result, by adding a newline to your format string or (if you don't want to output an extra newline) calling fflush(stdout):
printf("%s\n",line);
/* or */
printf("%s",line);
fflush(stdout);

Resources