Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- char leer_byte(FILE* f, int* seek_lectura) {
- fseek(f, *seek_lectura, SEEK_SET);
- char c = fgetc(f);
- *seek_lectura = ftell(f);
- return c;
- }
- char leer_byte_reversa(FILE* f, int* seek_lectura) {
- fseek(f, *seek_lectura, SEEK_SET);
- char c = fgetc(f);
- if (ftell(f) == 1) {
- fseek(f, 0, SEEK_SET);
- *seek_lectura = -1;
- } else {
- fseek(f, -2, SEEK_CUR);
- *seek_lectura = ftell(f);
- }
- return c;
- }
- void escribir_byte(FILE* f, int* seek_escritura, char c) {
- fseek(f, *seek_escritura, SEEK_SET);
- fputc(c, f);
- *seek_escritura = ftell(f);
- }
- void escribir_byte_reversa(FILE* f, int* seek_escritura, char c) {
- fseek(f, *seek_escritura, SEEK_SET);
- fputc(c, f);
- if (ftell(f) == 1) {
- fseek(f, 0, SEEK_SET);
- *seek_escritura = -1;
- } else {
- fseek(f, -2, SEEK_CUR);
- *seek_escritura = ftell(f);
- }
- }
- void desplazar_derecha(const char * file_name, long int offset) {
- FILE* f = fopen(file_name, "r");
- fseek(f, 0, SEEK_END);
- int seek_lectura = ftell(f) - 1; // Me paro en la ultima letra
- int seek_escritura = seek_lectura + offset;
- fclose(f);
- truncate(file_name, seek_escritura);
- f = fopen(file_name, "r+");
- while (seek_lectura >= 0) {
- char c = leer_byte_reversa(f, &seek_lectura);
- escribir_byte_reversa(f, &seek_escritura, c);
- }
- for (int i = 0; i < offset; i++){
- escribir_byte_reversa(f, &seek_escritura, '_');
- }
- fclose(f);
- }
- void desplazar_izquierda(const char * file_name, long int offset) {
- FILE* f = fopen(file_name, "r+");
- int seek_escritura = 0;
- int seek_lectura = offset * -1;
- fseek(f, 0, SEEK_END);
- size_t tam = ftell(f);
- fseek(f, 0, SEEK_SET);
- while (seek_lectura < tam) {
- char c = leer_byte(f, &seek_lectura);
- escribir_byte(f, &seek_escritura, c);
- }
- fclose(f);
- truncate(file_name, tam + offset);
- }
- void desplazar(const char * file_name, long int offset) {
- if (offset > 0)
- desplazar_derecha(file_name, offset);
- else if (offset < 0)
- desplazar_izquierda(file_name, offset);
- }
- int main(){
- desplazar("a.bin", -4);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement