I have a file with integers. I want to write in a buffer those integers as chars (its ascii number). Because it is part of a bigger project please do not post different but please help me on that. What I especially need is chars to be stored in a buffer of type char *.
These are my declarations.
FILE *in;
long io_len = 1000;
char * buffer;
in=fopen("input.txt","a+");
buffer = malloc(io_len * sizeof(*buffer));
if(buffer == NULL){
perror("malloc");
exit(EXIT_FAILURE);
}
I am figuring out 2 sollutions.
If I write this one:
read_ret = read(in, buffer, io_len);
it reads from file in, io_len bytes and stores them in buffer. But it reads characters. So for example if I write 123 it will write to buffer 1,2,3 not the character with ascii number 123.
So I did this:
while((fscanf(in,"%d", &i))==1){
printf(": %d\n", i);
}
which reads the integers as I want. Now I am a little bit confused on how I will store them in buffer, as characters. I have tried this but it get me a segmentation fault.
while((fscanf(in,"%d", &i))==1){
printf(": %d\n", i);
buffer=(char) i;
printf("Character in Buffer:%s\n",buffer);
buffer++;
}
Have in mind that later in my file I am writing my buffer somewhere else, so whatever I will do I want the pointer to be at the start of my char array(if it makes sense what I am saying)
Your final code should at least give you a warning about assigning an integer to a pointer in the line
buffer=(char) i;. It looks like you want to dereference the pointer.You are also printing a string when it looks like you really only want to print a character at a time.
Your code should probably look like this: