Created
June 30, 2015 18:14
-
-
Save seaneshbaugh/752073ff6c8cc0a1c76c to your computer and use it in GitHub Desktop.
Read file in reverse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| int main(int argc, char **argv) { | |
| // This is set to be really small since my test file is only 10 bytes long. | |
| size_t bufferSize = 4; | |
| char * buffer = (char *)calloc(bufferSize, sizeof(char)); | |
| if (!buffer) { | |
| printf("Could not allocate buffer.\n"); | |
| return 1; | |
| } | |
| FILE *file = fopen("n.txt", "rb"); | |
| if (!file) { | |
| printf("Could not open file.\n"); | |
| return 1; | |
| } | |
| fseeko(file, 0, SEEK_END); | |
| off_t fileSize = ftello(file); | |
| int i = 1; | |
| int bytesRead = 0; | |
| size_t offset; | |
| if (bufferSize >= fileSize) { | |
| offset = 0; | |
| } else { | |
| offset = fileSize - (bufferSize * i); | |
| } | |
| do { | |
| fseeko(file, offset, SEEK_SET); | |
| bytesRead = fread(buffer, 1, bufferSize, file); | |
| for (size_t j = 0, k = bytesRead - 1; j < k; j += 1, k -= 1) { | |
| buffer[j] = buffer[j] ^ buffer[k]; | |
| buffer[k] = buffer[j] ^ buffer[k]; | |
| buffer[j] = buffer[j] ^ buffer[k]; | |
| } | |
| printf("%.*s", bytesRead, buffer); | |
| if (offset == 0) { | |
| break; | |
| } | |
| i += 1; | |
| if (bufferSize * i > fileSize) { | |
| bufferSize = offset; | |
| offset = 0; | |
| } else { | |
| offset = fileSize - (bufferSize * i); | |
| } | |
| } while (bytesRead > 0); | |
| fclose(file); | |
| free(buffer); | |
| printf("\n"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment