Thread: Standard Input

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    7

    Standard Input

    I am having issue reading from standard input. In other words I want to run my program like: ./WordCount < Sample.txt

    Here is my code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(){
    
    
    FILE * file;
    char filename[1000], c;
    printf("Enter filename to read\n");
    scanf("%s", filename);
    file = fopen (filename, "r");
    if (file == NULL) {
    printf("Invalid File\n");
    exit(0);
    }
    c = fgetc(file);
    while (c != EOF){
    printf("%c", c);
    c = fgetc(file);
    }
    fclose(file);
    return(0);
    }
    I have been looking for hours and tried many options. Maybe I was not looking in the right place. I am not sure what I need to change in my code in order to read from standard input. I know that scanf reads from stdin but I want to use the redirection from a file command when running the program.

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    678

  3. #3
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,859
    Tips for debugging..

    1 - Can you open and close the file without an error when you manually put the file name in your code? Does the file exist?
    i.e.
    Code:
    ...=fopen("c:\\test.txt", "r");
    2 - Can you read one char from the file and print it?

    3 - Can you make a loop from step 2?
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 02-27-2013, 03:45 PM
  2. Replies: 4
    Last Post: 10-29-2011, 07:02 PM
  3. Standard input way?
    By Milhas in forum C Programming
    Replies: 6
    Last Post: 03-27-2008, 03:58 PM
  4. end of standard input
    By alphaoide in forum C++ Programming
    Replies: 5
    Last Post: 06-21-2004, 08:43 PM
  5. Getting standard input
    By winsonlee in forum C Programming
    Replies: 1
    Last Post: 04-04-2004, 08:51 PM

Tags for this Thread