fgets only returns 3 characters
This doesn't seem to be specific to any file; I tried it with an ordered list and once with "blah" in a file by itself. I got a count of 3 characters each time (after noticing only 3 characters and changing the output to their number instead).
I'm sure it's something uber-simple and so would appreciate help all the more. EDIT: I get a segfault when trying to output the string- or array-length of string in readLine...
EDIT2: OK, I figured out that my array's length isn't accessible to me after all... Passing the length separately fixes the problem.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void readLine(char* string, FILE* stream){
int i, length = sizeof(string);
fgets(string, length, stream);
char* last = &string[strlen(string) - 1];
if(((int)*last) == '\n'){
*last = 0;
}
return;
}
void concat(char* result, void (*callback)(char* result), char* array[]){
int i, sum = 0, length = sizeof(array);
for(i = 0; i < length; i++){
sum += strlen(array[i]);
}
result = calloc(sum, sizeof(char));
for(i = 0; i < length; i++){
if(array[i]){
strcat(result, array[i]);
}
}
callback(result);
free(result);
}
void interrupt(char* error){
fwrite(error, strlen(error), 1, stderr);
}
int main(int argc, char* argv[]){
if(argc < 2){
char* error = "Error: At least one argument (a filename) must be provided.";
fwrite(error, strlen(error), 1, stderr);
return 1;
}
char mode = 'r';
FILE* file = fopen(argv[1], &mode);
if(!file){
char* array[3];
array[0] = "Error: The file \"";
array[1] = argv[1];
array[2] = "\" could not be opened; please check its permissions and try again.";
char* error;
concat(error, &interrupt, array);
return 1;
}
char input[1024];
readLine(input, file);
printf("%d", strlen(input));
return 0;
}
Thanks!