Reputation: 63
Ok guys, the purpose of my program is to read from a text file called orginal.txt containing names in the format:
Kyle Butler
Bob Jones
Nathan Moore
The program then takes these names one at a time and turns them into something like:
[email protected]
This address is then stored line by line in a new text file called final.txt
problem is, i can't get it to work, it gives me a segmentation fault and does not even get to writing to 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;
}
Upvotes: 0
Views: 3700
Reputation: 2620
As mbratch wrote you write beyond 100 chars in line array. Here's a working code:
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]='@'; strcat(line, mod);
line[i+strlen(mod)]='\0';
}
}
FILE *fp2;
fp2 = fopen("final.txt", "a");
if (fp2 != NULL){
//fputs(line, fp2); printf("%s\n",line);
fprintf(fp2,"%s\n",line);
fclose(fp2);
}
}
fclose(fp);
return 0;
}
Upvotes: -1
Reputation: 121599
Suggested changes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100 /* Somehow parameterize "100" */
void write(char line[100]);
int main()
{
FILE *fp;
fp = fopen("original.txt", "r+");
if (!fp) { /* Check for error */
perror ("open failed");
return 1;
}
char line[MAXLEN];
/* You don't need hard-coded array length with a static string */
char *mod="@fakeemail.com\n";
while (fgets(line, MAXLEN, fp) != NULL){
int i;
/* You don't need to iterate through more characters than the string contains */
for(i=0; i<strlen(line); ++i){
if(line[i]==' '){
line[i]='.';
}
if(line[i]=='\n'){
line[i]='\0';
}
}
/* Move this OUTSIDE of your for loop */
strcat(line, mod);
/* Append to the output file */
FILE *fp2;
fp2 = fopen("final.txt", "a");
/* You're checking for error: good! */
if (fp2 != NULL){
fputs(line, fp2);
fclose(fp2);
}
}
fclose(fp);
return 0;
}
Upvotes: 0
Reputation: 58224
There are several problems with the code, but the segmentation fault is probably caused by this 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 the loop you are concatenating mod
to line
. Since you iterate the loop 100
times with no other option to quit the loop, and line
is only 100 characters long, very soon you will write past the 100th character of line
into some other part of memory.
Upvotes: 4