Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[C] using getchar() and putchar() to read in files

  1. Sep 11, 2014 #1
    Im working on some programme

    and I've used getchar() putchar() to read sentences in a text file

    I open the file usin stdin < filename.txt format

    and here is my code

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


    int main(int argc, char *argv[]) {

    int i;
    printf(" ");
    while((i=getchar())!='l'){
    putchar(i);
    }



    return 0;

    }

    and here is the first few sentences in the file

    "Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll

    This eBook is for the use of anyone anywhere at no cost and with"

    the code works fine for most part and prints out every single characters correctly including the space EXCEPT for "P" from Project in the first sentence

    it gets printed out in a very weird symbols

    can anyone help me figure out what is wrong
     
  2. jcsd
  3. Sep 11, 2014 #2

    ShayanJ

    User Avatar
    Gold Member

    You're not reading from a file. You're reading keyboard inputs and showing them on the screen. You even didn't open a file!
    Take a look at here.
     
  4. Sep 11, 2014 #3

    no I am not meant to open files in here
     
  5. Sep 11, 2014 #4

    ShayanJ

    User Avatar
    Gold Member

    But you said you want to read sentences from a file!!!
    Anyway, the code you posted, only reads keyboard inputs!!!
     
  6. Sep 11, 2014 #5

    Borek

    User Avatar

    Staff: Mentor

    He is reading from stdin, and if you look at how he calls his program, he reads from the file.
     
  7. Sep 11, 2014 #6

    Nugatory

    User Avatar

    Staff: Mentor

    Use 'od' or some similar program to look at the first few bytes in your input file.
     
  8. Sep 11, 2014 #7

    Borek

    User Avatar

    Staff: Mentor

    Are you sure it is a simple ASCII file and not UTF-8 file with BOM (http://en.wikipedia.org/wiki/Byte_order_mark )? [Broken]

    Edit: that's actually the same hint Nugatory gave, he was just faster. I hate being interrupted when posting grumpy_borek.png
     
    Last edited by a moderator: May 6, 2017
  9. Sep 11, 2014 #8

    NascentOxygen

    User Avatar

    Staff: Mentor

    Poster indicated in his opening post that he is using the operating system to perform redirection of file to stdin.
     
  10. Sep 12, 2014 #9
  11. Sep 12, 2014 #10
    then use a pipe
     
  12. Sep 12, 2014 #11
    forget about what I said it,s late and I'm tired.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [C] using getchar() and putchar() to read in files
  1. C++ csv file reading (Replies: 2)

Loading...