2

I am trying to get a user to enter a specific file name and have the program be able to read it.

FILE *fp;

char file[10];

fgets(file, sizeof(file), stdin);
fp = fopen(file, "r");

if (fp == NULL) {
    printf("File doesn't open\n");
    return 1;
}

This is a section of my code and what i'm currently trying to do. When i run the program and enter the file name, the output is "File doesn't open" which is my error message.

1
  • You should fprintf(stderr, "File %s did not open: %s\n", file, strerror(errno)); in case of error Commented Oct 24, 2015 at 3:13

3 Answers 3

3

The problem is that fgets also incorporates the newline character '\n' in the string read. You need to remove it,

char* p;
if(p = *strchr( file, '\n' ))
    *p = '\0';

otherwise fopen will fail.

Sign up to request clarification or add additional context in comments.

1 Comment

strchr returns NULL if the character isn’t found; you should probably check for that.
2

Assuming you meant fopen(file,...), before you can do that you must strip file of a newline. See man pages for fgets and [I suggest] strchr.

Comments

1

Use perror to print system error diagnostics:

int main(){
  FILE *fp;
  char file[10];

  fgets(file, sizeof(file), stdin);
  fp = fopen(file, "r");

  if (!fp) {
    perror(file);
    return 1;
  }
}

If you ask for file f, it'll print:

f
: No such file or directory

which should point you at the source of the problem (the fopen call may also fail for permissions reasons, for example).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.