简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM