Thread: File could not be opened while filename seems correct

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    1

    File could not be opened while filename seems correct

    I'm new to C and encountered a weird problem. Here's the code:

    Code:
    int main(){
    
        char name[]="";
    
    readname(name) ;
    printf("The filename is: %s\n",name);
    printf(name);
    printf("snazzyjazz.txt\n"); //error checking
    if (strcmp(name,"snazzyjazz.txt")>0) {
        printf("less");
    } else {
        puts("more");
    } //error checking
    FILE * my_stream;
    
    
    my_stream = fopen (name,"r+");
    Code:
    void readname (char  names[])
    {
        printf("Please enter the filename\n");
    
        fgets(names,30,stdin);
        printf("names = %s",names);
    
    }
    I compile this with no problem, but gives "File could not be opened". the strcmp tells me name and "snazzyjazz.txt" are not equal. but when I print them I get the same output. Rather confused.

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    fgets(names,30,stdin);
    If you input a filename with less than 29 characters, fgets() will also store the newline character.
    Try printing your name with:
    Code:
    printf("names = >>%s<<",names);
    and look carefully where the "<<" appear in the output.

    Bye, Andreas

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > char name[]="";
    Before you read in 30 chars, you'd better have 30 chars of space.
    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. Replies: 10
    Last Post: 10-14-2011, 01:31 PM
  2. C Delete opened file
    By gidion in forum C Programming
    Replies: 25
    Last Post: 12-04-2008, 10:35 AM
  3. in what position is a file opened?
    By grepawksed in forum C++ Programming
    Replies: 3
    Last Post: 01-21-2006, 03:41 PM
  4. Getting opened file paths
    By geek@02 in forum Windows Programming
    Replies: 6
    Last Post: 09-18-2005, 06:53 PM
  5. Rewriting an opened file.
    By Daghdha in forum C Programming
    Replies: 5
    Last Post: 06-13-2002, 01:55 AM