1
Guys I’m trying to do a programming challenge this one. It is not a very difficult challenge but my script does not have the expected behavior, in small files works but in larger files like 1GB I get segmentation fault
Analyzing with gdb the error is this:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7e55cb0 in __GI_fseek (fp=0x555555559220,
offset=900935887, whence=0) at fseek.c:35
35 fseek.c: No such file or directory.
Many will read and say "fseek does not find the directory or the file" However this script works with small files finds, maybe lost its way during the process.
My code is this:
#include <stdio.h>
#include <stdlib.h>
//O programa deve ler arquivos de qualquer tamanho e funcionar com um limite de
//512MB de memória (ler o arquivo inteiro em memória não é uma alternativa
//viável).
void reversePrint(char *sentence) {
long long i = 0;
while(sentence[i] != '\0') {
i++;
}
if((i> 0) && sentence[i-1] == '\n') {
i -= 2;
for(; i >= 0; i--) {
putchar(sentence[i]);
}
puts("");
}else {
for(; i >= 0; i--) {
putchar(sentence[i]);
}
puts("");
}
}
int main(int argc, char** argv) {
FILE *file;
char ch;
if( ! *++argv){
fputs("Usage: tac <file>\n",stderr);
exit(EXIT_FAILURE);
}
if((file = fopen(*argv, "r")) == NULL) {
perror("error openig file");
exit(EXIT_FAILURE);
}
fseek(file, 0, SEEK_END);
long size;
size = ftell(file);
char bufferLine[10000];
long j = 0;
for ( size -=2 ; size >= 0; size--) {
fseek(file, size, SEEK_SET);
if(ferror(file)) {
perror("seek error");
exit(EXIT_FAILURE);
}
bufferLine[j] = getc(file);
if((bufferLine[j] == '\n') || size == 0) {
bufferLine[j+1] = '\0';
reversePrint(bufferLine);
j = -1;
}
j++;
}
fclose(file);
return 0;
}
In order to test with the large file I referred to this is the download link
I really want to know why I’m getting this mistake.