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

C program help

  1. Dec 13, 2007 #1
    Total program to write number of characters to a file and to read those back.
    Please help.
  2. jcsd
  3. Dec 13, 2007 #2
    this is sudo code, not completely sure but most of it should work, provided you include the right libraries
    #include <file.h> ??? maybe

    file f = fopen ("text.txt", w); //opens for write
    for(int i = 1; i <=10; ++i;)
    fprintf(f,"a"); //prints a 10 times

    file f = fopen("text.txt", r); //opens for read

    Should get you started
  4. Dec 14, 2007 #3


    User Avatar
    Science Advisor
    Homework Helper

    fopen() opens a file, the second arguement should be a string, either "w" or "r" for write/read
    reading/writing individual characters you should look at fputc()/fgetc() or better fwrite()/fread().

    Take a look here http://www.cprogramming.com/tutorial/cfileio.html
    Last edited: Dec 14, 2007
  5. Dec 14, 2007 #4

    jim mcnamara

    User Avatar

    Staff: Mentor

    simplest but not the most efficient way:
    1. open the file for read only - explained above, get a file stream to read.
    2 set an integer variable as a counter = 0.
    3. while (fgetc(<file stream variable>)!=EOF) counter++;
    4. close the file
    5 display the number of characters (use the counter varaible) with printf

    The standard library functions you need are: fopen, fclose, printf, fgetc
    So you can read your documentation on how to call each of those
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook