0

The program reads the contents of the files specified as command line arguments. If the current argument causes an error (the file could not be opened), write an error message to the standard error output and continue execution with the following argument. The error message should be: File opening unsuccessful !.

#include <stdio.h>

int main() {

  
    char name[1024];

    scanf("%s",name);
    FILE* fp = fopen("name.txt", "r");
    if (fp !=0 ){
        printf("Open is successfull");
    } else {
        printf("File opening unsuccessful! \n");
    }
    fclose(fp);


}
topi12
  • 37
  • 5
  • Does this answer your question? [C - reading command line parameters](https://stackoverflow.com/questions/5157337/c-reading-command-line-parameters) – Passerby Nov 26 '21 at 23:02
  • You're not using the name provided by the input! And it would help to provide a useful error message. eg `fp = fopen(name, "r"); if( fp == NULL ){ perror(name); }` – William Pursell Nov 26 '21 at 23:04
  • The question has a contradiction. First you say you want to give the name with `scanf`, then the problem description says you should supply names as command line arguments. Which is it? – Passerby Nov 26 '21 at 23:04
  • So what means command line arguments ? I thought it is scanf. – topi12 Nov 26 '21 at 23:06
  • @topi12 see the first link in comments for command line arguments. Also use @ symbol when responding to comments, otherwise the person will not see it. – Barmak Shemirani Nov 26 '21 at 23:15
  • Your question in that title bares no relation to the problem you have. Clearly you know how to open a file because the code presented does exactly that. Rather you should ask how to process command line arguments. However, your comment reveals that you have no idea what a command line argument _is_! That is not a programming problem, rather a computer literacy question. – Clifford Nov 26 '21 at 23:16

1 Answers1

1

You don't want to use scanf to read from stdin, you need to use command line arguments as listed in the question.

C - reading command line parameters

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "%s\n", "Incorrect number of arguments");
        return 1;
    }

    FILE* fp = fopen(argv[1], "r");
    if (fp !=0 ){
        printf("File opening successful !\n");
        fclose(fp);
    } else {
        fprintf(stderr, "%s\n", "File opening unsuccessful !");
    }
}
codyne
  • 552
  • 1
  • 9