Segmentation fault in C txt file I/O -
ok guys, purpose of program read text file called orginal.txt containing names in format:
kyle butler bob jones nathan moore
the program takes these names 1 @ time , turns them like:
kyle.butler@emailaddress.com
this address stored line line in new text file called final.txt
problem is, can't work, gives me segmentation fault , not writing final.txt
#include <stdio.h> #include <stdlib.h> #include <string.h> void write(char line[100]); int main() { file *fp; fp = fopen("original.txt", "r+"); char line[100]; char mod[30]="@fakeemail.com\n"; while (fgets(line, 100, fp) != null){ int i; for(i=0; i<100; ++i){ if(line[i]==' '){ line[i]='.'; } if(line[i]=='\n'){ line[i]='\0'; } strcat(line, mod); } file *fp2; fp2 = fopen("final.txt", "a"); if (fp2 != null){ fputs(line, fp2); fclose(fp2); } } fclose(fp); return 0; }
there several problems code, segmentation fault caused for
loop:
for(i=0; i<100; ++i){ if(line[i]==' '){ line[i]='.'; } if(line[i]=='\n'){ line[i]='\0'; } strcat(line, mod); }
every time through loop concatenating mod
line
. since iterate loop 100
times no other option quit loop, , line
100 characters long, write past 100th character of line
other part of memory.
Comments
Post a Comment