I am trying to map a .img file, and I am not sure why my code is not working.
Here is my code, and when I run the code I keep getting my error, that p is equal to MAP_FAILED
int diskinfo(int argc, char* argv[]){
void *p;
char *size
if (argc < 2) {
printf("Please put ./diskinfo <file> \n");
exit(1);
}
int fp = open(argv[1],"rb+");
if(fp == NULL) {
printf("Error opening file");
exit(1);
}
struct stat buf;
fstat(fp, &buf);
p = mmap(NULL,buf.st_size, PROT_READ, MAP_PRIVATE, fp, 0);
if(p == MAP_FAILED){
printf("Error mapping memory\n");
exit(1);
}}
If anyone has any suggestions on where my code is wrong or if I am missing a piece of information I would be very grateful.
Changing to perror() does not work. Also changing this function doesn't change the fact that p is still equal to MAP_FAILED
if(p == MAP_FAILED){
return;
}
I changed the below what is the solution:
int fp = open(argv[1],O_RDWR);
if(fp < 0){
. . .
But I am still returning
It is unclear from the state of your question whether you were ever able to get
mmapto work. Your last edit added:Which is fine if you are writing back to the file you have opened, but if not, you should open using
O_RDONLYto prevent inadvertent modification of your original file.While not an error,
fpis generally used as a file pointer associated with file stream operations when the file is opened withfopen. Here you are using low-level I/O withread/writewhich uses a file descriptor instead of a stream pointer. When referencing a descriptor, the general vernacular usesfdas short-hand for file descriptor. (personally, it was awkward to see the two used in a interchanged manner -- which I suspect is the case for others as well)Your remaining use of
fstat, the resultingbuf.st_sizeand your call tommapare not the problem. Your problem lies elsewhere -- which is one of the primary reasons you should post A Minimal, Complete, and Verifiable Example (MCVE).That said, to insure you have incorporated your changes in the proper manner, I'll leave you with a simple example that
mmaps a file and simply dumps the file tostdout(so limit your input filenames to a reasonably short text file to work with the example -- otherwise you will see all sorts of strange characters). Work through the following:(note: your check of
if (argc < 2)should really be done in the calling function,main()here. There is no reason to calldiskinfountil you have validated you have a filename to open. You could actually refactor your code to check the arguments andopenthe file inmain()and simply pass an open file-descriptor todiskinfoas a parameter)Example Use/Output
Look things over and let me know if you have any questions. If you still cannot get your function to work, then post a MCVE so that we can help further.