Skip to content

Instantly share code, notes, and snippets.

@muhasturk
Last active September 18, 2023 03:13
Show Gist options
  • Save muhasturk/28b5069dd422803232ef to your computer and use it in GitHub Desktop.
Save muhasturk/28b5069dd422803232ef to your computer and use it in GitHub Desktop.
Reverse File
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
FILE *file;
file = fopen("./oz.txt", "r+");
if (file == NULL)
{
printf ("Error - Couldn't open file\n");
}
fseek(file, 0, SEEK_END); // move file pointer to end of file
long size = ftell(file); // file pointer position == character count in file
fseek(file, 0, SEEK_SET); // move back to beginning of file
char* buffer = (char*) malloc(size * sizeof(char));
fread(buffer, sizeof(char), size, file); // read file contents to buffer
for(long i = 0; i < size/2; ++i)
{
buffer[i] = buffer[size-i-1];
}
fseek(file, 0, SEEK_SET); // The fread set the file pointer to the end so we need to put it to the front again.
fwrite(buffer, sizeof(char), size, file); // Write reverted content
free(buffer);
fclose(file);
return 0;
}
@woojunro
Copy link

woojunro commented Mar 24, 2020

It does not reverse all of the texts in your file, just half of them. Did u intend to do so?

@muhasturk
Copy link
Author

Hey, this piece of 'c' code was written 5 years ago and I could remember what yo asked.

@Torokh
Copy link

Torokh commented Sep 18, 2023

If you need full text then replace 22 for(long i = 0; i < size/2; ++i) to for(long i = 0; i < size; ++i)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment