Linux programming: writing to a device file

I wrote this:

#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <mtd/mtd-user.h>
#include <errno.h>

int main( void )
{
        int fd;
        char buf[4]="abc";

        fd = open("/dev/mtd0", O_RDWR);
        lseek(fd, 1, SEEK_SET);
        write(fd, &buf, 4);
        close(fd);
        perror("perror output:");

        return 0;
}

The / dev / mtd0 file is created using the nandsim kernel module and runs

mtdinfo /dev/mtd0

got a significant result. After starting my program, it displays:

perror output:: Invalid argument

If my program has any errors?

+3
source share
5 answers

Yes, there is a problem. Your use perror()is incorrect.

You must first check if the system call indicates a problem before calling perror. The personal page is in sufficient detail devoted to the topic:

Note that errno is undefined after a successful library call: this call
may  well  change  this  variable, even though it succeeds, for example
because it internally used some other  library  function  that  failed.
Thus,  if  a failing call is not immediately followed by a call to per‐
ror(), the value of errno should be saved.

You should check return codes for each system and only call perror if they fail. Something like that:

fd = open("/dev/mtd0", O_RDWR);
if (fd < 0) {
    perror("open: ");
    return 1;
}
if (lseek(fd, 1, SEEK_SET) < 0) {
    perror("lseek: ");
    return 1;
}
if (write(fd, &buf, 4) < 0) {
    perror("write: ");
    return 1;
}
close(fd);
+2
source

You should have something like this

if(-1 == write(fd, &buf, 4)){
  perror("perror output:");
}
close(fd);

because perror shows the last error.

http://www.cplusplus.com/reference/clibrary/cstdio/perror/

perror http://www.java-samples.com/showtutorial.php?tutorialid=597

+1

, 4 .

, dmesg . :

nand_do_write_ops:

mtd :

char buf[2048]="abcdefghij";                      //Ajust size according to 
                                                  //mtd_info.writesize
mtd_info_t mtd_info;                              // the MTD structure

if (ioctl(fd, MEMGETINFO, &mtd_info) != 0) {...   // get the device info

memset(buf+10, 0xff, mtd_info.writesize - 10);    //Complete buf with 0xff's

if (write(fd, &buf, mtd_info.writesize) < 0) {... // write page

Also consider checking for bad blocks ( ioctl(fd, MEMGETBADBLOCK, ...) and deleting blocks ( ioctl(fd, MEMERASE, ...) before you write.

Hope this helps.

+1
source

The problem is in this line:

if (write(fd, &buf, 4) < 0) {

The second parameter to call the record should be a pointer, "buf" is already a pointer, referring to it by "&". you get a pointer to the wrong pointer: the right call:

if (write(fd, (void*)buf, 4) < 0) {
0
source

All Articles