Register | Login
Views: 19364387
Main | Memberlist | Active users | ACS | Commons | Calendar | Online users
Ranks | FAQ | Color Chart | Photo album | IRC Chat
11-02-05 12:59 PM
0 user currently in Programming. | 3 guests
Acmlm's Board - I2 Archive - Programming - Delete a byte.
  
User name:
Password:
Reply:
 

UserPost
HyperLamer
Posts: 6616/8210
Bah, I was hoping I wouldn't have to resort to copying the file (even if only into memory).
Dish
Posts: 540/596
As beneficii suggested --- I dont' know of a way to remove a single byte rather than reading/adjusting/rewriting the whole file either =/

Although I just thought I'd chime in and say that for large chunks of data, fread() and fwrite() are more preferable to fgetc() and fputc()
beneficii
Posts: 440/567
Originally posted by HyperHacker
Presumably a really simple question, but I can't seem to find an answer. How can I delete a byte from the middle of a file (in Binary mode, in C)?


My solution would be to store the file size in memory (like an int variable), load the file into memory, starting at the byte after the byte you're trying to delete shift every byte one byte left, decrement the file size, and then save the file.

EDIT: Here's some code that probably does what you are describing. It's untested, but I think that it probably works:


#include <malloc.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>

int deletebyte(const char *filename, int address) {
int size, handle, *data;
FILE *nfo;

handle = open(filename, O_RDONLY); /* getting file size */
size = filelength(handle);
close(handle);

data = malloc(sizeof(int) * size); /* creating data space in memory to store file*/

nfo = fopen(filename, "rb"); /* loading the file */
for(int i = 0; i < size; i++)
data[i] = fgetc(nfo);
fclose(nfo);

for(int i = address + 1; i < size; i++) /* starting at the byte following the specified address */
data[i - 1] = data[i]; /* shifting each byte left */

size--; /* decrementing the size */

nfo = fopen(filename, "wb"); /* reopening the file to write to it */
for(int i = 0; i < size; i++) /* writing to it */
fputc(data[i], nfo);
fclose(nfo);

/* now that we did it, it's time to return our value and free our dynamically allocated array */

free(data);

return size; /* returning our new file size */
}

/* if you want to use this function call it: the first parameter is the file name and the second parameter is the address that you want to delete; the function returns an int, the new filesize of the file. */
HyperLamer
Posts: 6614/8210
Presumably a really simple question, but I can't seem to find an answer. How can I delete a byte from the middle of a file (in Binary mode, in C)?
Acmlm's Board - I2 Archive - Programming - Delete a byte.


ABII


AcmlmBoard vl.ol (11-01-05)
© 2000-2005 Acmlm, Emuz, et al



Page rendered in 0.009 seconds.