Thread: Can't open file

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    1

    Unhappy Can't open file

    Hi,
    I'm having a problem openning a file. My code seems to work fine on the files that I have created, but won't open a file that my
    instructor gave me. The file is a bunch of hex values(which really
    shouldn't matter) and has a .dat extention. I thought that
    possibly the extention was a problem, so I created a new .txt
    file, then copied and pasted the data. My code would not open the new file either . Here is my code:

    #include <stdlib.h>
    #include <stdio.h>
    void main(void)
    {
    FILE *fptr1;
    char fname[]="Virtual_Machine.txt",c='y',ch,dum,out[20];
    int i=0;
    if((fptr1 =fopen(fname, "r"))==NULL)
    {
    printf("Cannot open %s.\n",fname);
    exit(1);
    }
    while((c!='n')&&((ch=fgetc(fptr1))!=EOF))
    {
    printf("char is: %c \n",ch);
    out[i]= ch;
    printf("char is: %c \n",out[i]);
    printf("CONTINUE?:\n");
    c=getchar();
    dum=getchar(); //flushes newline
    }
    fclose(fptr1);
    }

    Any insight would be greatly appreciated.
    Thanks,
    Darren

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Instead of the non-informative
    Code:
    printf("Cannot open %s.\n",fname);
    try using perror instead. It should tell you why the file can't be opened. Chances are that the program is looking in a different location that where the file is.

    >void main(void)
    void main is only valid if you're on a freestanding implementation. Since you're learning C, this is highly unlikely. Use one of these:
    Code:
    int main(void) /* No arguments */
    int main(int argc, char **argv) /* Command line arguments */
    And of course, return an integer value at the end.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    76
    Though the ANSI C standard no longer distinguishes text and binary files, for compatibility reasons change the fopen call to:

    Code:
       fopen(fname,"rb")

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Though the ANSI C standard no longer distinguishes text and binary files
    What section, paragraph, and line did you read this from?
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM