Reputation: 1
I continue to have a segmentation fault when I try and execute the following code...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if (argc < 4){
fprintf (stderr,"usage message");
return (1);
}
FILE *src = fopen(argv[1],"r"); //file pointer to inputFile
FILE *outputFile = fopen(argv[2],"w"); //file pointer to outputFile
int nth = atoi(argv[3]); //nth term value
printf("nth term is %d",nth);
int c;
int currNum;
int currCount = 1;
c = fscanf(src, "%d\n",currNum); //read ints line by line
while( c == 1 ){
fscanf(src,"%d\n",currNum);
++currCount;
if (currCount % nth == 0){
fprintf (outputFile, "%d\n", currNum);
}
}
}
I'm not sure if I have to somehow convert argv[1] and argv[2] before I can use them as the file names.
Upvotes: 0
Views: 651
Reputation: 46
giving input parameters to "fscanf"
is wrong. check below one.......
c = fscanf(src, "%d\n",currNum); // wrong
c = fscanf(src, "%d\n",&currNum);
fscanf(src,"%d\n",&currNum);
Upvotes: 1
Reputation: 4758
You can use atoi to convert to int
int nth = atoi( argv[3] );
You also can NULL
check file* src and outfile. If you are not giving correct paths then fopen
may fail.
Upvotes: 0
Reputation: 8839
Did you provide a command line argument? You should check that by using an if
statement before opening the files. For example, you could add
if ( argc < 4 )
{
printf ( stderr, "usage message\n" );
return ( 1 );
}
Also, change that stoi
for argv[3]
to atoi
.
You don't need to add \n
for fscanf
. Just "%d"
will do fine.
Upvotes: 1