I am experiencing a segfault using fopen(). My code is below.
void encoding(char otext[], char ibin[]){
//Some characters for storage:
char c, h, a, r;
unsigned int x;
//Check if file is available:
FILE *in;
FILE *out;
in = fopen("in.txt", "r");
if (in==NULL){
printf("Error: No input file\n");
exit(1);
}
out = fopen("out.txt", 'w');
if (out==NULL){
printf("Error: No output file\n");
exit(1);
}
//Scanning the file:
while(!feof(in)){//While not at the end of the in file
fscanf(in, "%c", &c);
fscanf(in, "%c", &h);
fscanf(in, "%c", &a);
fscanf(in, "%c", &r);
x = pack(c,h,a,r);
fprintf(out, "%u", x);
//fwrite(&x,sizeof(int),1,out);
}
//Close file
fclose(in);
fclose(out);
}
unsigned int pack(char c1, char c2, char c3, char c4){//Works
int bits = 8;
unsigned int x = c1;
x = (x << bits) | c2;
x = (x << bits) | c3;
x = (x << bits) | c4;
return x;
}
unsigned int encrypt(unsigned int x){//Works
int i = 0;
while (i < KEY){
unsigned int temp = x;
x = (x<<1);
if (temp > x){
x += 1;
}
i+=1;
}
return x;
}
I found this topic: Segfault while using fopen - which suggests that the issue may be in using fprintf() incorrectly. So I commented out the fprintf() line and simply had it set to open and close out, like so:
//Edit for clarity: I commented out everything BUT the 3 lines of
//code below, and I still got the segfault.
/*...*/
File *out;
out = fopen("out.txt", "w");
/*...*/
fclose(out);
Even this causes a segfault, leading me to believe the issue is not in my use of fprintf(). At this point I'm at a loss.