phyrrus9
phyrrus9

Reputation: 1467

write() not writing to device

code:

#include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>

void write_zero(char * file, unsigned long bytes)
{
    printf("Zeroing %s\n", file);
    unsigned int wrote = 0, total = 0;
    int fd, i, buf;
    char obj = 0x00;

    fd = open(file, O_RDWR, DEFFILEMODE);
    lseek(fd, 0, SEEK_SET);
    write(fd, &obj, bytes);
}

int main(int argc, char * * argv)
{
    int fd;
    unsigned long blocks = 0;
    char check = 0x0;

    fd = open(argv[1], O_RDONLY);
    ioctl(fd, BLKGETSIZE, &blocks);
    close(fd);

    printf("Blocks: %lu\tBytes: %lu\tGB: %.2f\n",
            blocks, blocks * 512, (double)blocks * 512.0 / (1024 * 1024 * 1024));
    do
    {
            printf("Write 0x0 to %s? [y/N] ", argv[1]);
            fflush(stdout);
    }
    while (scanf("%c", &check) < 1);
    if (check == 'y')
    {
            write_zero(argv[1], blocks * 512);
    }
}

I get nothing actually written to the device.. I copied my open line from the 'dd' source code, thinking maybe it was not opened right. dd can zero the device, but this program does not. Any ideas?

Upvotes: 0

Views: 184

Answers (1)

Charlie Burns
Charlie Burns

Reputation: 7044

It seems like this has been beaten to death but

char obj = 0x00;

fd = open(file, O_RDWR, DEFFILEMODE);
lseek(fd, 0, SEEK_SET);
write(fd, &obj, bytes);

Is not going to write zeros. It's going to write garbage from the stack.

Upvotes: 2

Related Questions