LGG
LGG

Reputation: 538

Reading string from command line argument in MPI c

I have to write an MPI c program. My compiler does not recognize datatype string though I have added string.h . I want to read a string from the command line and pass it to the function given below

int find_rows(char * file)
{
    int  length=0;
    char buf[BUFSIZ];
    FILE *fp;
    fp=fopen(file, "r");
    while ( !feof(fp))
    {
         // null buffer, read a line
        buf[0] = 0;
        fgets(buf, BUFSIZ, fp);
        // if it's a blank line, ignore
        if(strlen(buf) > 1) 
        {
            ++length;
        }

    }
    fclose(fp); 
#ifdef DEBUG
    printf("lFileLen = %d\n", length);
#endif
return    length;     

}

This function works when I have

 char file[50] = "m5-B.ij";

and then call

nvtxs = find_rows(&file );

But gives me segmentation fault when I give

 nvtxs = find_rows(argv[1] );

Can someone please help ?

Upvotes: 0

Views: 858

Answers (1)

user1944441
user1944441

Reputation:

Instead of

find_rows(&file );

call

find_rows(file );

file is already a pointer. You were passing the address of the pointer to the function.

Then later in the function find_rows you try to open invalid file and operate with fp which is a null pointer causing undefined behaviour.

EDIT

Your call nvtxs = find_rows(argv[1] ); is correct. The problem is fp=fopen(file, "r"); might not be able to open the file, if the file does not exist or it cannot find the file.

Upvotes: 1

Related Questions