Malek Haddad
Malek Haddad

Reputation: 13

C program that reads a file the user inputs and returns the first line

#include <stdio.h>
int main (int argc, char **argv)
  {
    FILE* file;
    char scratch[1024];
    char filename[1024] = argv[1];
    file = fopen( filename, "r" );
    if( file != NULL ){  
        if( fgets( scratch, 1024, file ) != NULL ){    
            fprintf( stdout, "read line: %s", scratch );  
        }  
        fclose(file);
    return 0;
  }
}

Essentially if the user was to run ./nameOfTheProgram nameOfTheTextFile it should return the first line of the Text File

I'm getting the following error: error: invalid initializer char filename[1024] = argv[1];

Upvotes: 0

Views: 48

Answers (1)

alinsoar
alinsoar

Reputation: 15793

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
     ... your variables
     char *filename;

     if (argc>1)
     {
         filename = argv[1];
     }
     else
     {
         fprintf(stderr, "need a filename\n");
         exit(1);
     }

     ... your code
     return 0;
}

Upvotes: 2

Related Questions