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 file /dev/mtd0 is created using nandsim kernel module, and run
mtdinfo /dev/mtd0
got meaningful output.After i run my program, it's output:
perror output:: Invalid argument
If there is any error in my program?
You should have something like this
if(-1 == write(fd, &buf, 4)){
perror("perror output:");
}
close(fd);
because perror shows last error.
http://www.cplusplus.com/reference/clibrary/cstdio/perror/
and more about perror http://www.java-samples.com/showtutorial.php?tutorialid=597
Yes, there is a problem. Your use of perror()
is wrong.
You should first check if a system call indicates a problem before calling perror. The man page is quite explicit on the subject:
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 be checking the return codes of each system, and only call perror if they fail. Something like this:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With