Add read portion of file

This commit is contained in:
Raffaele Mignone 2021-03-27 12:55:39 +01:00
parent c2baf5fa05
commit 072ad792f1
Signed by: norangebit
GPG Key ID: F5255658CB220573
2 changed files with 26 additions and 0 deletions

View File

@ -52,4 +52,28 @@ char *read_file(char *filepath, int *len) {
fclose(f);
return content;
}
char *read_file_portion(char *filepath, int size, int rank, int *portion_len) {
FILE *f = fopen(filepath, "r");
fseek(f, 0, SEEK_END);
int total_len = ftell(f) - 1;
int len = total_len / size;
int start_point = rank * len;
int end_point = start_point + len;
if (rank + 1 == size)
end_point += total_len % size;
*portion_len = end_point - start_point;
char *content = (char *) malloc(sizeof(char) * (*portion_len));
fseek(f, start_point, SEEK_SET);
fread(content, 1, *portion_len, f);
fclose(f);
content[*portion_len] = '\0';
return NULL;
}

View File

@ -11,4 +11,6 @@ int sum_array(int *, int);
char *get_text_file(int argc, char **argv);
char *read_file_portion(char *filepath, int size, int rank, int *portion_len);
#endif //KMP_UTIL_H