Ok, I have been troubleshooting this with my teacher/tutor all day and I have it compiling but its giving a segmentation fault. I used GDB to see the issue and its says its with strlen().
If someone could point me in the right direction I would appreciate it. Not looking for the answer, I want to understand what I'm doing wrong. Thanks in advance
Here is my code:
Code:
// usage: ./gloriousStringLab [filename]
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR 64
void print_string(char *str);
void write_string(char *str, FILE *fp2);
int main(int argc, char *argv[]) {
FILE *fp, *fp2;
char *strings[MAX_STR];
int string = 0;
char temp[MAX_STR];
int len, size = 0;
int i, j;
if(argc != 2) {
printf("You're doing it wrong.\n");
printf("usage: %s [filename]\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "r");
if(fp == NULL) {
printf("Unable to open file: %s\n", argv[1]);
return 1;
}
//read each string from file
while(fscanf(fp, "%s", temp) > 0){
//malloc enough space in strings for string HINT STRLEN
len = strlen(temp);
strings[string] = malloc(len);
//place string in strings HINT STRCPY
strcpy(strings[string], temp);
memset(temp, '\0', len);
string++;
}
string = string-1;
fclose(fp);
//print array to reverse
for(i = string; string > 0; i--){
printf("%s ", strings[i]);
}
printf("\n");
//write to argv[1]reversed.txt USE write_str
fp2 = fopen("reversed.txt", "w+"); //having issues here...
for(j = 0; j < string; j++){ //having issues here...
write_string(strings[j], fp2);
j+=j;
}
fclose(fp2);
//gg
return 0;
}
void write_string(char *str, FILE *fp2) {
fprintf(fp2, "%s ", str);
}
void print_string(char *str) {
printf("%s ", str);
}