I would like to write an address in a text file, which can be read by fscanf
and dereferenced by C after reading the pointer. How do I write the address in the file?
edit: i don't mean to be rude, but i know that this is exactly what i need, so if anyone can please just list the answer, and not ethical reasons for why i shouldn't be doing this, that would be great!
further edit: ah, i was misclear about what I want to do. In emacs, I want to (with my fingers!!) write in an address that a C program could read in using fscanf and use as a pointer. How do I physically (with my fingers!!) write an address in emacs. For example, if I wanted C to read in 0x11111111
, I am trying to write 0x11111111
in emacs, but it's not becoming the right address in C when i read it in.
fprintf(file, "%p", pointer);
should do the job; but it is questionable if the address is of any use, if you read the file...
Perhaps for some hardware register / IO-port or shared memory this could be interesting, but in the general case: do not use it. Segfault, sense-less data or data-corruption will be the result...
[added]
fscanf(... "%x" ...)
should read a hexadecimal coded integer, aka address.
You can't do it. There is no guarantee the pointer will be valid when it is read in in again - if it is read by another process it almost certainly won't be. And if it is read by the same process, why write it to a file in the first place?
I don't see the problem, here is the snippet using a string instead of a file:
#include <stdio.h>
int main() {
void *p1,*p2;
p1 = (void*)0x12FE0FE0A;
char str[] = "12FE0FE0A";
sscanf(str, "%p", &p2);
printf("%p %p\n",p1,p2);
}
the pointers are identical.
BTW, if you write "0x12345678", the format string should be "0x%p"
to process correctly the "0x" prefix.
Something like this maybe?
#include<stdio.h>
int main()
{
FILE *out = fopen("test.out","w");
int i = 6;
int *pi = &i;
fprintf(out, "%d", pi);
fclose(out);
printf("pi points to an int that has the value of %d\n", *pi);
FILE *in = fopen("test.out","r");
fscanf(in, "%d", &pi);
fclose(in);
printf("After reading the value of pi from the file, it points to an int that has the value of %d\n", *pi);
}
If you only want to read the value, then this is all you should care about:
int *pi;
fscanf(in, "%d", &pi);
// use *pi to dereference normally
Edit to your further edit : try using "%x"
to read in a hex number.
You can assign an integer value to a pointer type so you use a type cast, eg
unsigned char *vram = (unsigned char *)0xA0000000;
The caveat being that the result is implementation-defined (not undefined, mind you), and might not even be usable.
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.