views:

192

answers:

4

I read the input file , which has 911 lines , and want to copy these 911 lines into the output file , after making a few changes to each line..

I am getting segmentation fault when i run this.. I dont know why.. can anyone please help..

#include<stdio.h>
void main()
{
    int i;
    FILE *fin,*fop;char* str;
    fin=fopen("atk561011.txt","r");
    if(fin=NULL) printf("ip err");
    fop=fopen("svmip.txt","w");
    if(fop=NULL) printf("op err");
    for(i=1;i<=911;i++)
    {
        fgets(str,150,fin);
        if((i>300&&i<=360)||(i>600&&i<=660)) 
            str[7]='1';
        else 
            str[7]='0';
        fputs(str+7,fop);
        putc('\n',fop);
    }
    fclose(fin);
    fclose(fop);
}
+5  A: 

For a start, this is wrong:

if(fin=NULL)

Should be:

if (fin == NULL)

(the same goes for fop, of course). And if you didn't succeed opening the file - don't just print an error, exit, because what are you going to read from? Keep in mind that the output of printf is buffered and in case of a segfault you won't always see it at all, even if it ran before the fault.

Another thing: you don't allocate memory for str, yet write into it with fgets.

And another thing: reading a pre-defined amount of lines from the file is probably a bad idea. It's better to read from the input until there is an end of file, or until a required amount of lines has been read.

Eli Bendersky
Also fop=NULL.. In C, = is assign, == is compare.
Chris Kannon
It's generally safer to just test against the pointer "if (fop)" will return true if fop isn't null, or "if (!fop)" if you want to test for a failure
Martin Beckett
This is why I've moved to the idiom "if (NULL == var)...".
Steve Emmerson
@Steve, I personally dislike it, too unnatural. Readability is important too...
Eli Bendersky
@Eli, Considering all the styles I've encountered, I've decided that "readability" is in the eye of the beholder. Also, this idiom saves my bacon at least once a week. :-)
Steve Emmerson
A: 

Both fin=NULL and fop=NULL should both be using the 'equal-equal' operator. You're setting fin and fop to NULL instead of checking for a bad return value.

Mark Pauley
+1  A: 

Your not allocating any space for the pointer str.

Change that to either char str[/*Max Length You expect 150? */] or allocate the buffer.

In the meantime your code is walking all over memory - thus the segmentation fault.

Ruddy
+1  A: 
tommieb75
By the way, what is the purpose of str+7?? Have edited the code to highlight this.
tommieb75
Thanks for that , now it is working.. I just wanted to automate this manual work i had to do now.. This code was not meant to solve any general problem.. < that str+7 is to avoid copying the first 7 chars > to the new file.
trinity