Thread: if anyone can tell me what's wrong with this code

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    1

    if anyone can tell me what's wrong with this code

    it suppose to put all the ascii codes for 1 to 255 in the files and then read it back
    it got stuck at i=26 in the reading process
    10x
    Code:
    #include <stdio.h>
    
    void main()
    {
      FILE *fp;
      int i;
      int c;
      fp=fopen("d:\\1.txt","w");
      for(i=1;i<=255;i++)
      {
        fputc(i,fp);
      }
      fclose(fp);
      fp=fopen("d:\\1.txt","r");
      for(i=1;i<=255;i++)
      {
    
          c=fgetc(fp);
          printf("&#37;d\n",c);
      }
      fclose(fp);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Ctrl-Z (ASCII number 26) can be interpreted as end of file in Windows. You can try opening the file in binary format to prevent that sort of thing. (I would also expect you to get an extra 10, since I think ASCII 13 would get written to a text file as 10 & 13. Or maybe fputc doesn't do that.)

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Also, void main is wrong.

    > Or maybe fputc doesn't do that.
    It will, but then fgetc will undo it and the expected result will be seen.
    But the file will be 256 bytes long, not 255.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 07:10 AM
  2. what is wrong with this code please
    By korbitz in forum Windows Programming
    Replies: 3
    Last Post: 03-05-2004, 10:11 AM
  3. I cant find what is wrong with this code
    By senegene in forum C Programming
    Replies: 1
    Last Post: 11-12-2002, 06:32 PM
  4. Anyone see what is wrong with this code?
    By Wise1 in forum C Programming
    Replies: 2
    Last Post: 02-13-2002, 02:01 PM
  5. very simple code, please check to see whats wrong
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-10-2001, 12:51 AM