PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label stdin. Show all posts
Showing posts with label stdin. Show all posts

Monday, October 31, 2022

[FIXED] How do you detect ctrl+D in C?

 October 31, 2022     c, eof, fgets, segmentation-fault, stdin     No comments   

Issue

So I read in a line using fgets

line = fgets(l, BUFSIZ, stdin);

And I from what I understand control+d is EOF so I tried

if(line[0] == EOF)
     continue;

to get back to the top of the loop. But this led to segfaults... Is there another way?


Solution

Since the machine generates EOF on Ctrl + D, you should be checking fgets() for NULL, as fgets() is obliged to return NULL on end of file.

line = fgets(l, BUFFSIZ, stdin)
if (line == NULL)
    continue;

In your code, you are trying to dereference a pointer that's NULL leading to segfault.



Answered By - Arjun Sreedharan
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to read input from stdin until EOF read line by line with each line containing four space separated integers in C

 October 31, 2022     c, eof, input, stdin, unix     No comments   

Issue

How to read input from stdin until EOF read line by line with each line containing four space separated integers in C. It could be inputted by commands like this:

$ echo 1 2 3 4 | ./myProgram

or

$ cat file.txt
1 2 3 4
0 -3 2 -4

$ ./myProgram < file.txt
"This is where it would output my calculations"

Then I want to save the individual integers to int variables.

char strCoordinates[101];
    char *ptr;
    int coordinates[4];
    long int tempCoordinates;
    while(scanf("%s", strCoordinates) != EOF) {
        tempCoordinates = strtol(strCoordinates, &ptr, 10);
        int lastDigit = 0;
        for (int x = 4; x >= 4; x--) {
            lastDigit = tempCoordinates % 10;
            coordinates[x] = lastDigit;
            tempCoordinates = (tempCoordinates - lastDigit) / 10;
            }
    }

This is what I was trying but it seems way to complicated . . .

Any help would be greatly apprecated. Not sure whether to use scanf(), sscanf(), fscanf(), gets()


Solution

Examples of One way

char strCoordinates[101];
char *ptr;
int coordinates[4];
while(fgets(strCoordinates, sizeof(strCoordinates), stdin) != NULL) {
    char *s = strCoordinates;
    for (int x = 0; x < 4; x++) {
        coordinates[x] = strtol(s, &ptr, 10);
        s = ptr;
    }
    printf("%d,%d,%d,%d\n", coordinates[0],coordinates[1],coordinates[2],coordinates[3]);
}


Answered By - BLUEPIXY
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I force eof on stdin?

 October 31, 2022     c++, eof, stdin     No comments   

Issue

For a C++ application, how can I programmatically force an end of file (EOF) on stdin?


Solution

Actually, you cannot. As long as you can read data from stdin, EOF hasn't been reached, and in fact you can never reach it. You can close the stdin itself, however. To close it, do this:

fclose(stdin);

After this, you cannot read data from stdin.



Answered By - Nawaz
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does the Linux(?)-Terminal not "consume" '\n' EOF?

 October 31, 2022     c, eof, getchar, stdin, terminal     No comments   

Issue

From what I've read, the Linux terminal (in default settings) buffers the input and only sends it after receiving either EOF or '\n'.

When I loop c = getchar(); and check each c for being EOF (end then break) I need to do CTRL-D twice in order to stop reading, as the first EOF is always consumed by the terminal (I know one can change the terminal to raw, but maybe this is a bit overkill).

However, when I check for c being '\n' (which also sends the input) it will not be consumed.

Example:

  • Input: "abc\n"
    • Characters read: 'a','b','c','\n'
  • Input: "abc" and Ctrl-D
    • Characters read: 'a','b','c'
  • Input: "abc", Ctrl-D and Ctrl-D again
    • Characters read: 'a','b','c',EOF
  • Input: "abc", Return and Ctrl-D
    • Characters read: 'a','b','c','\n',EOF

Isn't this highly inconsistent? Or is there any rationale behind it?

I want to parse input including whitespaces and thus cannot check for '\n' but for EOF - is that possible without changing the terminal to raw?

I've tried with feof(stdin) too, but apperently this doesn't work either :/


Solution

That's not how it works. ^D sends on the currently buffered line, so if you don't hit it immediately after a newline, your program will not see an empty read and will not know the input is ended. So you need another ^D to send nothing. But your program never sees a ^D.

In fact you can use stty to change the terminal's EOF character, so that for example ^N will end the input; your program will run exactly the same, because it does not depend of the value of the EOF keyboard character.

PS. Since you were trying to write a C program: the input calls return EOF when they try to read a file, and get an empty buffer (0 characters). In fact, EOF is not ^D as you imagine, but -1: This value was chosen because it does not fit in a byte, while read() could legally return any possible byte (yes, even '\04' aka ^D). This is why the signature of getchar() says it returns an int.



Answered By - alexis
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How i can stop reading values after EOF

 October 31, 2022     c, eof, getchar, stdin     No comments   

Issue

I have little problem with my code. I try to make 'while' loop which will read all my input values and then stop when i clicked EOF. I have read that EOF in windows is CTRL+Z and so on but my 'while' doesn't want to stop and after all input values and CTRL+Z, it stay and wait for next values. This is my code and hope you will help me thanks):

#include <stdio.h>
#include <stdbool.h> 

#define gc getchar



inline int scan_integer();
inline void zaprzeczenie(bool*);


int main() {
  bool rosnie=true;

  int poprzednia;
  register int terazniejsza;


  terazniejsza = scan_integer();
  poprzednia = terazniejsza;

  int sumaAktualnego=terazniejsza;
  int sumaNajwiekszego=terazniejsza;

  int iloscAktualnego=1;
  int iloscNajwiekszego=0;

  int staly=1;
  int sumaStalego=0;


  while(!feof(stdin))
  {
    printf("%d ",terazniejsza);
    terazniejsza = scan_integer();


    if(terazniejsza<poprzednia){
        if(rosnie){
            if(iloscAktualnego>iloscNajwiekszego){
                iloscNajwiekszego=iloscAktualnego;
                sumaNajwiekszego=sumaAktualnego;
            }
            iloscAktualnego=1;
            sumaAktualnego=terazniejsza;

            if(staly>1){
                iloscAktualnego+=staly;
                sumaAktualnego+=sumaStalego;
                staly=1;
                sumaStalego=0;
            }

            zaprzeczenie(&rosnie);
        }
        else{
            sumaAktualnego+=terazniejsza;
            iloscAktualnego++;
        }
    }
    else if(terazniejsza>poprzednia){
        if(rosnie){
            sumaAktualnego+=terazniejsza;
            iloscAktualnego++;
        }
        else{
            if(iloscAktualnego>iloscNajwiekszego){
                iloscNajwiekszego=iloscAktualnego;
                sumaNajwiekszego=sumaAktualnego;
            }
            iloscAktualnego=1;
            sumaAktualnego=terazniejsza;

            if(staly>0){
                iloscAktualnego+=staly;
                sumaAktualnego+=sumaStalego;
                staly=1;
                sumaStalego=0;
            }

            zaprzeczenie(&rosnie);
        }
    }
    else if(terazniejsza==poprzednia){
        staly++;
        sumaStalego+=poprzednia;
        sumaStalego+=terazniejsza;
        sumaAktualnego+=terazniejsza;
        iloscAktualnego++;
    }

    poprzednia=terazniejsza;
}
  if(iloscAktualnego>iloscNajwiekszego){
      iloscNajwiekszego=iloscAktualnego;
      sumaNajwiekszego=sumaAktualnego;
  }

  printf("%d %d",iloscNajwiekszego, sumaNajwiekszego);
 }

 inline int scan_integer()
{
  register int c = gc();
  int wejsciowa = 0;
  for( ; ((c<48 || c>57)); c = gc() );

  for( ;c>47 && c<58; c = gc() ) {
      wejsciowa = (wejsciowa << 1) + (wejsciowa << 3) + c - 48;
  }
  return wejsciowa;
}

inline void zaprzeczenie(bool* boo){
  boo=!boo;
}

P.S.:Sorry for polish variables)


Solution

#define gc getchar

Please don't do this - it makes it harder for others to read and understand your code.

while( !feof( stream )) doesn't work the way most people expect it to, and will wind up looping one too many times. Instead, you need to check the result of your last input operation. Since you're using getchar, you can check the result of that:

while ( (terazniejsza = scan_integer()) != EOF )
{
  ...
}

...

inline int scan_integer()
{
  register int c = gc();
  int wejsciowa = 0;
  for( ; ((c<48 || c>57) && c != EOF ); c = gc() );

  for( ;c>47 && c<58 && c != EOF; c = gc() ) {
      wejsciowa = (wejsciowa << 1) + (wejsciowa << 3) + c - 48;
  }
  return c != EOF ? wejsciowa : c;
}    


Answered By - John Bode
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why use EOF to check if stdin buffer is cleared

 October 31, 2022     c, eof, stdin     No comments   

Issue

Say I have the following...

int main () {     
   char name [5] = "";
   char c;
   printf("Enter a name: ");
   fgets(name,5,stdin);
   while ((c = getchar()) != '\n');
   printf("Exiting...);
   getchar();
   return 0;
}

The while loop will clean the stdin buffer but I have seen the loop done like this as well...

while ((c = getchar()) != '\n' && c != EOF);

I am wondering if there is any difference between the 2??? Does testing for EOF make any difference?


Solution

I am wondering if there is any difference between the 2??? Does testing for EOF make any difference?

Yes, testing c != EOF makes a tremendous difference. getchar() returns EOF in the event that it detects an error or end-of-file on the standard input. Both of those are entirely possible. Once getchar() returns EOF, it is likely to return EOF again on every subsequent call, so the version that does not test for EOF is at risk of going into an infinite loop.



Answered By - John Bollinger
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 30, 2022

[FIXED] How to exit stdin when EOF is reached in C programming

 October 30, 2022     arrays, c, eof, getchar, stdin     No comments   

Issue

I'm having troubles with my program. The aim of it is to read an input of numbers from the user, and when they stop inputting numbers (ctrl-d) it collects the inputted numbers and prints out 'Odd numbers were: blah blah' and 'Even numbers were: blah blah'.

I'm having trouble with how to exit the program at EOF and when it feels like I have overcome that problem, another problem occurs which is my program doesn't print the numbers from the array. It only prints 'Odd numbers were:' and 'Even numbers were:'.

Any help is appreciated. Thanks

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void) {
int n, i, array[1000];
    i=0;
    while (i = getchar() !=EOF) {
        scanf("%d", &array[i]);
        i++;
    }   
    printf("Odd numbers were:");
    i=0 ;
    while(i = getchar() != EOF) { 
        if(array[i]%2!=0) {
            printf(" %d", array[i]);
            i++;
        }
    }
    printf("\nEven numbers were:");
    i=0 ;
    while(i = getchar() !=EOF) { 
        if (array[i]%2==0) {
            printf(" %d", array[i]);
            i++;
        } 
    }
        printf("\n");
return 0;
}

Solution

Performing Single-Digit Conversion to int

You may be making things a bit harder on yourself than it needs to be. While you can use while (scanf ("%d", &array[i]) == 1) to read whitespace separated integers and avoid having to perform a manual conversion, if your intent is to read single-digits, then using getchar() is fine. (for that matter, you can read any multi-digit integer with getchar(), it is simply up to you to provide a conversion from the ASCII characters to final numeric value)

The manual conversion for single-digit characters is straight forward? When you read digits as characters, you are not reading the integer value represented by the digit, you are reading the ASCII value for the character that represents each digit. See ASCII Table and Description. In order to convert a single ASCII character digit to it's integer value, you must subtract the ASCII value of '0'. (note: the single-quotes are significant)

For example if you read a digit with int c = getchar();, then you need to subtract '0' to obtain the single-digit integer value, e.g. int n = c - '0';

When filling an array, you must ALWAYS protect against writing beyond the bounds of your array. If you declare int array[1000] = {0}; (which has available zero-based array indexes of 0-999), then you must validate that you never write beyond index 999 or Undefined Behavior results. To protect your array bounds, simply keep track of the number of indexes filled and test it is always below the number of array elements available, e.g.

while (n < MAX && (c = getchar()) != EOF)   /* always protect array bounds */
    if ('0' <= c && c <= '9')               /* only handle digits */
        array[n++] = c - '0';               /* convert ASCII to int */

Next, while you are free to test n % 2 (using the modulo operator), there is no need (little endian). Since any odd number will have its ones-bit set to 1, all you need is a simple bitwise comparison, e.g (7 in binary is 0111).

    if (array[i] & 1)                       /* if ones-bit is 1, odd */
        printf (" %d", array[i]);

Of course, for even numbers, the ones-bit will be 0 (e.g. 8 in binary is 1000), so the corresponding test can be:

    if ((array[i] & 1) == 0)                /* if ones-bit is 0, even */
        printf (" %d", array[i]);

Putting all of the pieces together, you can store all single digits read in array and then segregate the even and odd numbers for printing in a very simple manner (note: neither stdlib.h or math.h are required),

#include <stdio.h>

#define MAX 1000   /* define a constant rather than use 'magic' numbers in code */

int main (void)
{
    int array[MAX] = {0},
        c, i, n = 0;

    while (n < MAX && (c = getchar()) != EOF)   /* always protect array bounds */
        if ('0' <= c && c <= '9')               /* only handle digits */
            array[n++] = c - '0';               /* convert ASCII to int */

    printf ("\narray        : ");               /* output array contents */
    for (i = 0; i < n; i++)
        printf (" %d", array[i]);

    printf ("\narray - odd  : ");
    for (i = 0; i < n; i++)
        if (array[i] & 1)                       /* if ones-bit is 1, odd */
            printf (" %d", array[i]);

    printf ("\narray - even : ");
    for (i = 0; i < n; i++)
        if ((array[i] & 1) == 0)                /* if ones-bit is 0, even */
            printf (" %d", array[i]);

    putchar ('\n');                             /* tidy up w/newline */

    return 0;
}

Example Compilation with Warnings Enabled

$ gcc -Wall -Wextra -pedantic-std=gnu11 -Ofast -o bin/arrayevenodd arrayevenodd.c

Example Use/Output

$ echo "01234567890123456789" | ./bin/arrayevenodd

array        :  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
array - odd  :  1 3 5 7 9 1 3 5 7 9
array - even :  0 2 4 6 8 0 2 4 6 8

Look things over and let me know if you have further questions.


Performing Manual Multi-Digit Conversion to int

If you are needing to convert multi-digit integers from characters, the easy way is to use a function that provides the conversion for you (e.g. the scanf family of functions or by using line oriented with fgets or getline and parsing and converting the strings of digits with strtok and then strtol, or parsing with sscanf, etc.)

However, performing a manual conversion of individual characters read by getchar() into a multi-digit integers is straight forward. You simply check for a valid character than can begin an integer (including the prefixes of +/-) and sum each digit providing a proper offset for the place of the digit by increasingly multiplying the sum by 10 before adding (or actually subtracting if building a the sum as a negative sum for coding efficiency purposes) each digit until you reach the next non-digit and then you add the final sum to your array and advance the array index.

While building the sum, it is up to you to check for integer Overflow before adding the final sum to your array. (you can handle the overflow condition however you like, the example below just throws the error and exits)

The manual conversion probably adds about 20 lines of code, e.g.

#include <stdio.h>
#include <stdint.h> /* exact length types */
#include <limits.h> /* INT_X constants */

#define MAX 1000    /* define constant rather than use 'magic' number in code */

int main (void)
{
    int array[MAX] = {0},
        c, i, start = 0, sign = 1, n = 0;
    int64_t sum = 0;

    while (n < MAX && (c = getchar()) != EOF) { /* always protect array bounds */
        if (!start) {                           /* flag to start building int  */
            start = 1;                          /* flag - working on int */
            if (c == '+')                       /* handle leading '+' sign */
                continue;
            else if (c == '-')                  /* handle leading '-' sign */
                sign = -1;
            else if ('0' <= c && c <= '9')      /* handle digits */
                sum = sum * 10 - (c - '0');     /* note: sum always computed */
            else                                /*       as negative value   */
                start = 0;                      /* reset - char not handled  */
        }
        else if ('0' <= c && c <= '9') {        /* handle digits */
            sum = sum * 10 - (c - '0');         /* convert ASCII to int */
            if (sum < INT_MIN || (sign != -1 && -sum > INT_MAX))
                goto err;               /* check for overflow, handle error */
        }
        else {                          /* non-digit ends conversion */
            if (sum)                    /* if sum has value, add to array */
                array[n++] = sign != -1 ? -sum : sum;
            sign = 1;                   /* reset values for next conversion */
            start = 0;
            sum = 0;
        }
    }
    if (sum)    /* add last element to array on EOF */
        array[n++] = sign != -1 ? -sum : sum;

    printf ("\narray        : ");               /* output array contents */
    for (i = 0; i < n; i++)
        printf (" %d", array[i]);

    printf ("\narray - odd  : ");
    for (i = 0; i < n; i++)
        if (array[i] & 1)                       /* if ones-bit is 1, odd */
            printf (" %d", array[i]);

    printf ("\narray - even : ");
    for (i = 0; i < n; i++)
        if ((array[i] & 1) == 0)                /* if ones-bit is 0, even */
            printf (" %d", array[i]);

    putchar ('\n');                             /* tidy up w/newline */

    return 0;

    err:

    fprintf (stderr, "error: overflow detected - array[%d]\n", n);
    return 1;
}

Example Use/Output

$ echo "1,2,3,5,76,435" | ./bin/arrayevenodd2

array        :  1 2 3 5 76 435
array - odd  :  1 3 5 435
array - even :  2 76

Example with '+/-' Prefixes

$ echo "1,2,-3,+5,-76,435" | ./bin/arrayevenodd2

array        :  1 2 -3 5 -76 435
array - odd  :  1 -3 5 435
array - even :  2 -76

Look over the new example and let me know if you have any more questions.



Answered By - David C. Rankin
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How does EOF act in getchar() and scanf() on Windows system?

 October 30, 2022     c, eof, stdin     No comments   

Issue

I have two pieces of codes to test how the two console I/O functions, getchar() & scanf(), handle the EOF. But I still do not have a clear comprehension about the actual operations behind the outputs and their behaviors. Can someone explains that for me? Thanks a lot! (I am using Windows OS)

// 1st piece of Code
#include <stdio.h>
#include <ctype.h>

int main(void)
{
   char ch;

   while ((ch=getchar()) != EOF)
   {
      putchar(toupper(ch));
   }

   return 0;
} 

If I type

abc

or

abc(ctrl+z)

The program will have the same outputs:

ABC


// 2nd piece of Code
#include<stdio.h>

int main(void)
{
    int x;
    while(scanf("%d",&x) != EOF)
    {
        /*Ctrl + z + Enter*/
        printf("x=%d\n",x);
    }
    return 0;
}

If I type

123

The program will output:

x=123

Otherwise, if I type

123(ctrl+z)

The program will have an infinite output:

x=123

x=123

x=123

x=123

...


Solution

getchar() returns the value of the character converted to unsigned char or EOF in case of error.

The error can be "end of file" or something else; usually (for getchar()) the programmer does not care about the error, just that an error happened.


scanf() returns the number of values matched and assigned (basically the number of % in the format string) or EOF in case of error. Note that the number can be less than the number of % in case, for example, of badly formatted input

Just like for getchar() the error can be "end of file" or something else. Particularly, reading less than the number of % is not an error.

So you may prefer to test for the correct number of assignments rather than testing for error in scanf()

#include <stdio.h>

int main(void) {
    int x;
    while (scanf("%d", &x) != 1) {
        /*Ctrl + z + Enter*/
        printf("x=%d\n", x);
    }
    return 0;
}


Answered By - pmg
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to detect EOF when input is not from a file?

 October 30, 2022     eof, python, python-3.x, stdin     No comments   

Issue

I'm working through the HackerRank 30 days of code and I'm on day 8. The challenge is to take n lines of standard input of the form name phone-number and add these to a dictionary in key : value pairs of the format name : phone-number. That part was fine.

The next part of the input is an arbitrary number of lines, each containing a name. The task is to print the phone-number of each name or print "Not found" if the name is not in the dictionary.

My trouble lies in determining the end of the input.

The second part of my code is as follows:

counter = 0 # To prevent infinite loop
while 1:
    query = input()
    if query in phone_book:
        print("{}={}".format(query, phone_book[query]))
    elif query not in phone_book:
        print("Not found")
    else:
        break
    counter += 1
    if counter == 10000000:
        break

The if and elif statements check whether or not the name is in the dictionary and the else statement is meant to break out of the loop if there is no more input. However, I get an EOFError: EOF when reading a line error. My code passes all the tests, but I know there should be a better way to deal with the EOF than just setting an upper limit of 10000000 lines (if the input was more than 10000000 lines, I could just increase the counter limit, but I know that is not a good way of doing this).

I've looked at this page: How to find out whether a file is at its `eof`?

But I don't know how to implement this in my code, since the HackerRank input doesn't seem to be in a file from which I can read lines.

How could I manage the EOF issue and eliminate the need for a counter?

NB. The link to the HackerRank page: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem


Solution

Just iterate over sys.stdin; then there is no need to explicitly check for the end of the input; the iterator will raise StopIteration when it reaches the ed of the input.

import sys

for query in sys.stdin:
    query = query.strip()
    if query in phone_book:
        print("{}={}".format(query, phone_book[query]))
    else:
        print("Not found")


Answered By - chepner
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to inject EOF for stdin on Git bash on windows 10?

 October 30, 2022     eof, git-bash, stdin, windows-10     No comments   

Issue

I have tried the following keys: Ctrl+D, Ctrl+C, and Ctrl+Z. The programming I am running on bash doesn't stop unless EOF is reached.


Solution

Following worked for me:

Ctrl+Z, and then press Enter.



Answered By - hashmap
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send EOF to stdin in paramiko?

 October 30, 2022     eof, paramiko, python, stdin     No comments   

Issue

I would like to execute some program through ssh and redirect its input from a file. The behaviour of the following code:

channel.exec_command('cat')
with open('mumu', 'r') as f:
    text = f.read()
    nbytes = 0
    while nbytes < len(text):
        sent = channel.send(text[nbytes:])
        if sent == 0:
            break
        nbytes += sent

should be equivalent to (assuming public-key authentication):

 ssh user@host cat < mumu

However the application hangs waiting for more input. I think this happens because the stdin stream is never closed. How do I do that?


Solution

Call shutdown() (or shutdown_write()) on the channel.



Answered By - Roger Pate
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I read from standard input again after an EOF?

 October 30, 2022     c, eof, haskell, io-monad, stdin     No comments   

Issue

I have the following C program:

#include <stdio.h>
#include <unistd.h>

void readAndEchoAll(void) {
    for(;;) {
        char buf[100];
        ssize_t size = read(STDIN_FILENO, buf, sizeof(buf));
        if(size <= 0) {
            return;
        }
        fwrite(buf, 1, size, stdout);
    }
}

int main(void) {
    puts("Reading and echoing STDIN until first EOF...");
    readAndEchoAll();
    puts("Got first EOF. Now reading and echoing STDIN until second EOF...");
    readAndEchoAll();
    puts("Got second EOF.");
    return 0;
}

When I run it, it works the way I want it to. Here's what it does:

Reading and echoing STDIN until first EOF...
asdf
^Dasdf
Got first EOF. Now reading and echoing STDIN until second EOF...
fdsa
^Dfdsa
Got second EOF.

I'm trying to create an equivalent Haskell program. Here's my attempt:

readAndEchoAll :: IO ()
readAndEchoAll = do
    buf <- getContents
    putStr buf

main :: IO ()
main = do
    putStrLn "Reading and echoing STDIN until first EOF..."
    readAndEchoAll
    putStrLn "Got first EOF. Now reading and echoing STDIN until second EOF..."
    -- ???
    readAndEchoAll
    putStrLn "Got second EOF."

This doesn't work. Here's what it does:

Reading and echoing STDIN until first EOF...
asdf
^Dasdf
Got first EOF. Now reading and echoing STDIN until second EOF...
readtwice.hs: <stdin>: hGetContents: illegal operation (handle is closed)

How do I make this work like the C program? I assume that I need to put some equivalent of clearerr(stdin); where I have -- ???, but I'm not sure what that equivalent is.

Update: Turns out clearerr is a bit of a red herring, as it's exclusive to the standard C API. When using the POSIX API, you can just read again without needing to do anything equivalent to it. So rather than make Haskell do anything extra, I need to make it not do something: not prevent further reads once it sees EOF.


Solution

You can't use getContents, because hGetContents (semi-)closes the handle it's passed and getContents calls hGetContents. But there's no problem with reading from a handle again after EOF with most of the other functions from the standard library. Here's a simple but inefficient example of reading all the characters without using getContents:

import Control.Exception
import System.IO.Error

readAll = go [] where
    handler cs err = if isEOFError err
        then return (reverse cs)
        else throwIO err
    go cs = catch (do
        c <- getChar
        go (c:cs))
        (handler cs)

main = do
    all <- readAll
    putStrLn $ "got: " ++ all
    putStrLn "go again, mate"
    all <- readAll
    putStrLn $ "got: " ++ all

If you want better efficiency, there are various functions available for reading lines-at-a-time or other large chunks in the standard library, rather than one character at a time.



Answered By - Daniel Wagner
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to programmatically stop reading from stdin?

 October 30, 2022     c, eof, pthreads, stdin     No comments   

Issue

fgetc() and other input functions can return when there's no data on the file descriptor. This can be simulated for console applications reading from stdin typing Ctrl-D on keyboard (at least on unix). But how to do it programmatically? For example, how to return from the fgetc() in the reader thread in the following code (NB: ignore the possible race condition)?

#include <pthread.h>
#include <stdio.h>

void* reader()
{
    char read_char;
    while((read_char = fgetc(stdin)) != EOF) {
        ;
    }

    pthread_exit(NULL);
}

int main(void)
{
    pthread_t thread;
    pthread_create(&thread, NULL, reader, NULL);

    // Do something so the fgetc in the reader thread will return

    pthread_exit(NULL);
}

Thanks!


Solution

It seems you want a threads to stop blocking on fgetc(stdin) when some event occurs to handle that event instead. If that's the case you could select() on both stdin and some other message pipe so that the thread can handle input from both:

fd_set descriptor_set
FD_ZERO(&descriptor_set); 
FD_SET(STDIN_FILENO, &descriptor_set); 
FD_SET(pipefd, &descriptor_set); 

if (select(FD_SETSIZE, &descriptor_set, NULL, NULL, NULL) < 0) 
{ 
  // select() error
} 

if (FD_ISSET(STDIN_FILENO, &descriptor_set)) {
  // read byte from stdin
  read(STDIN_FILENO, &c, 1);
}

if (FD_ISSET(pipefd, &descriptor_set)) 
  // Special event. Do something else

Also note that only one thread in your process should be reading from stdin.



Answered By - Alex Jasmin
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to take variable input from stdin in C++

 October 30, 2022     c++, eof, getline, stdin, string     No comments   

Issue

I was trying to take input variable number of strings and numbers.Found this solution link:

I tried this for numbers:

#include<iostream>
using namespace std;
int main(){
    int np;
    while (cin>>np){
        cout << np<<endl;
    }
    return 0;
}

for strings:

#include<iostream>
#include<string>
using namespace std;
int main(){
    string line;
    while (getline(cin, line)){
        cout << line <<endl;
    }
    return 0;
}

But,when I run the code,even if I just press enter it doesn't come out of the loop.The loop should terminate if just an enter key is pressed,but that does not happen.

Please provide suggestions how to achieve this functionality.


Solution

You can write

while (std::getline(std::cin, line) && !line.empty()) {
    // ...
}

Only keep looping when the fetched string is nonempty.



Answered By - timrau
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] How to send STDIN twice to Popen process, each time with EOF?

 October 29, 2022     eof, popen, python, stdin, subprocess     No comments   

Issue

I have this part of a code:

for stdin in stdins:
    p.stdin.write(stdin)

which writes string stdin to process p's STDIN.

The challenge is: the process p expects to see EOF before it goes to next STDIN.

With the loop above, the problem is that subsequent p.stdin.write(stdin) will be considered by the process p as input of the 1st STDIN input collection. Because, as said earlier, p expect to see an EOF before moving to subsequent fields.

So, my question is: how to solve this problem in Python? The process needs to see something like:

for stdin in stdins:
    p.stdin.write(stdin)
    p.stdin.send_eof()

Constraints: solution must not use pexpect.


Solution

EOF is not a character, it just means there is no more data to read.

As such I don't believe what you're after is possible in Python or most other languages.



Answered By - pishpish
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I signal EOF to close stdin under the Git Bash terminal on Windows? Ctrl-D didn't work

 October 29, 2022     bash, eof, git, stdin, terminal     No comments   

Issue

I'm writing a command line tool. One of the things this tool can do (certainly not uniquely) is read it's input from stdin. I was testing this interactively (by typing input, rather than cat'ing a file in) when I noticed that I have no clue how to signal EOF to it.

I have spent an inordinate amount of time tonight Googling this and found nothing helpful. I searched SO, as well. Please feel free to point me to a duplicate question, but I did my due diligence, I promise.

EDIT: It might be helpful (?) to mention that I'm doing this on Windows. So I believe the terminal is more or less a branded MinGW?


Solution

If you're trying to send EOF to a program's input under Windows, Ctrl-Z is what you're looking for.



Answered By - Brendan Dolan-Gavitt
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to run c++ and javascript client code (hackerrank style) on local machine

 October 29, 2022     c++, eof, javascript, node.js, stdin     No comments   

Issue

I am working on learning C++ and Javascript by solving Hackerrank problems. Right now C++ compiles but when I run it stalls. The same with my JavaScript. I would like to learn to feed in data for test cases like they do on the platform. For example: If I have this code in C++:

#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
vector<string> split_string(string);

// Complete the countApplesAndOranges function below.
void countApplesAndOranges(int s, int t, int a, int b, vector<int> apples, vector<int> oranges) {
    int count_a = 0;
    int count_b = 0;
    for (int i = 0; i < apples.size(); i++){
        // apples[i] += a;
        apples[i] += a;
        if (s <= apples[i] && apples[i] <= t )
            count_a +=1;

        // cout << apples[i] << ;
    }
    // for (auto i: apples)
    //     // cout << i << ' ';

    // cout << endl;    
    for (int i = 0; i < oranges.size(); i++){

        // apples[i] += a;
        oranges[i] += b;
        if (s <= oranges[i] && oranges[i] <= t )
            count_b +=1;
        // cout << oranges[i] << "";
    }
    // for (auto i: oranges)
    //     // cout << i << ' ';

    cout << count_a << endl;
    cout << count_b;



}

int main()
{
    string st_temp;
    getline(cin, st_temp);

    vector<string> st = split_string(st_temp);

    int s = stoi(st[0]);

    int t = stoi(st[1]);

    string ab_temp;
    getline(cin, ab_temp);

    vector<string> ab = split_string(ab_temp);

    int a = stoi(ab[0]);

    int b = stoi(ab[1]);

    string mn_temp;
    getline(cin, mn_temp);

    vector<string> mn = split_string(mn_temp);

    int m = stoi(mn[0]);

    int n = stoi(mn[1]);

    string apples_temp_temp;
    getline(cin, apples_temp_temp);

    vector<string> apples_temp = split_string(apples_temp_temp);

    vector<int> apples(m);

    for (int i = 0; i < m; i++) {
        int apples_item = stoi(apples_temp[i]);

        apples[i] = apples_item;
    }

    string oranges_temp_temp;
    getline(cin, oranges_temp_temp);

    vector<string> oranges_temp = split_string(oranges_temp_temp);

    vector<int> oranges(n);

    for (int i = 0; i < n; i++) {
        int oranges_item = stoi(oranges_temp[i]);

        oranges[i] = oranges_item;
    }

    countApplesAndOranges(s, t, a, b, apples, oranges);

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}

How would I go about "feeding" it inputs.

Similarly, for the JavaScript:

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the countApplesAndOranges function below.
function countApplesAndOranges(s, t, a, b, apples, oranges) {
    let count_a = 0
    let count_b = 0

    for (let i = 0; i < apples.length; i++){
        apples[i] += a

        if (s <= apples[i] && apples[i] <= t)
            count_a += 1

    }
    for (let i = 0; i < oranges.length; i++){
        oranges[i] += b
        if (s <= oranges[i] && oranges[i] <= t)
            count_b += 1

    }


    console.log(count_a)
    console.log(count_b)
}

function main() {
    const st = readLine().split(' ');

    const s = parseInt(st[0], 10);

    const t = parseInt(st[1], 10);

    const ab = readLine().split(' ');

    const a = parseInt(ab[0], 10);

    const b = parseInt(ab[1], 10);

    const mn = readLine().split(' ');

    const m = parseInt(mn[0], 10);

    const n = parseInt(mn[1], 10);

    const apples = readLine().split(' ').map(applesTemp => parseInt(applesTemp, 10));

    const oranges = readLine().split(' ').map(orangesTemp => parseInt(orangesTemp, 10));

    countApplesAndOranges(s, t, a, b, apples, oranges);
}

I understand I could do this manually - by hardcoding local-variables to main() but I would like to learn about C++ - getline() function as well as JavaScript - process.stdin.

Thank you in advance for the help.


Solution

I figured out the C++, you have to add the input: eg.

7 11 
5 15
3 2
-2 2 1
5 -6

It must be the exact number of lines as there are variables, or redirect the input from a file ie.

$ ./a.out < input.txt

For the JavaScript you must either: Redirect the input:

$ node program.js < input.txt

or add lines and press to signify the end of input stream.



Answered By - tsm
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do i have to input EOF 3 times when using fgets?

 October 29, 2022     c, eof, fgets, stdin, while-loop     No comments   

Issue

So basically I want to copy everything i write to stdin (including newline char) to string for hash purposes. I managed to accomplish that and made small code to represent my problem.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFERSIZE 10000

int main()
{
char *myStr = calloc(1,1);
char buffer[BUFFERSIZE];

while( fgets(buffer, BUFFERSIZE , stdin) != NULL ){
  myStr = realloc(myStr, strlen(myStr)+1+strlen(buffer) );
  strcat( myStr, buffer );
}
printf("\n%s\n",myStr);

}

everything works when I enter some text then press ENTER and after I call EOF.

But when I start program enter "a" then I try to call EOF (using Ctrl Z + ⏎ (Windows cmd prompt), Ctrl D (Linux)) I have to do it three times for program to actually break the loop. I was expecting maximum of 2 times.

Can someone explain how using EOF, stdin and fgets works? Or should I use something else (for example getline)? I am sorry if I am not clear about my problem, just ask anything you need.

Thank you.


Solution

First of all, ^Z or ^D are control characters that mean something to the terminal you are using, and sometimes that means for the terminal to signal end-of-file condition.

Anyway, your three keypresses are processed by the terminal to take the following actions, after entering text:

  1. Flush the input (i.e. send the characters that have been input so far from the terminal to the program - by default this doesn't happen as the terminal uses line buffering)
  2. Set end-of-file condition
  3. Set end-of-file condition again

Inside your program that corresponds to:

  1. Nothing happens: even though a is received, fgets keeps reading until end-of-file or newline
  2. fgets completes because of end-of file. However it does not return NULL because characters were read, "a" to be specific.
  3. A bug in old versions of glibc causes fgets to try to read again, even though it previously reached end-of-file. fgets completes because of end-of-file, and returns NULL because there were no characters read.


Answered By - M.M
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 15, 2022

[FIXED] How to pass STDIN to a program and store its output to a variable? C

 September 15, 2022     bash, c, exec, stdin, system-calls     No comments   

Issue

I need to execute a file from the bash using and store its output to a variable, there's also the needs to pass to its stdin a string s. Something like this in bash:

    usr:~$ s | program args

I know how to call the program and give him args:

    execvp(program,args);

So my problem is giving to that his stdin and store output to a variable(string)!

P.S.:can't use system and popen.


Solution

Some example code for you to experiement. This excute ls | cat.

 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main(int argc, char** argv) {
     int fd[2];
     int pid;
     char* cmd1[2] = {"ls", NULL};
     char* cmd2[2] = {"cat", NULL};
     int status;

     pid = fork();
     if (pid == 0) {
         pipe(fd);
         pid = fork();
         if (pid == 0) {
             printf("cmd1\n");
             dup2(fd[1], 1);
             close(fd[0]);
             close(fd[1]);
             execvp(cmd1[0], cmd1);
             printf("Error in execvp\n");
         }
         else {
             dup2(fd[0], 0);
             close(fd[0]);
             close(fd[1]);
             printf("cmd2\n");
             execvp(cmd2[0], cmd2);
             printf("Error in execvp\n");
         }
     }
     else {
         close(fd[0]);
         close(fd[1]);
         wait(&status);
         printf("%d\n", status);
         wait(&status);
         printf("%d\n", status);
     }
 }




Answered By - Bruce Shen
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing