What's wrong with my code here???

This is a discussion on What's wrong with my code here??? within the C Programming forums, part of the General Programming Boards category; Hello, everybody. Need help with this program. It's meant to take a pattern 1 and replace the first occurance in ...

What's wrong with my code here???

Hello, everybody. Need help with this program. It's meant to take a pattern 1 and replace the first occurance in a string with pattern 2. The patterns are case sensitive. I keep getting a segmentation fault.

First thing, use some vertical white space (aka, blank lines) to separate separate sections of the program.

> string = (char*) malloc (101);
Do not cast malloc in C, see the FAQ for why not.

> if (!feof(inFILE))
Also a bad idea, and it's also in the FAQ
Simply opening a file (even one with zero length) will not set feof() to return true, so in this respect it is a useless test (it will always pass).

> strncat (outFILE,str,5);
Whilst modifying argv strings is allowed (I think), making them larger is full of all sorts of problems since you've no idea how much space is allocated to each one, beyond the \0 at the end of each string.
If it's laid out in memory as
arg1\0arg2\0arg3\0
then modifying arg1 trashes arg2

> out = open(outFILE, O_RDWR|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR);
Why the change from using fopen?
Mixing styles is not usually a good idea.

> strncat (string2, replace2, strlen(replace2));
You have to be pretty careful with strncat. Whilst it helps prevent buffer overflows, you also have to make sure that a \0 is copied as well (which strncat doesn't always do).

> outFILE = argv[1]; //Gets the name of the file.
> strncat (outFILE,str,5); //Adds .out to that end of the file.
You're still strncating to argv. As Salem said, this is a bad idea. You should make outFile a char array like you did with str, making it big enough to hold whatever length string the final product will contain. Then use strcpy for this line:
> outFILE = argv[1];

Also, I'm not sure if I'm doing the error checking correctly. The way I'm doing it is print an appropriate error message on standard error and exiting, right??? Also, am I checking all the possible errors???