C - print in Stream array byte with variable size - c

I'm designing a system where I read from a SD card and send the information via Bluetooth.
To do that, firstly I ready data from a SD card and store the bytes in an array byte of a fixed length:
char final_name[17];
And to send it via Bluetooth, I defined the Bluetooth as a stream, and I'm calling printf to send data:
fprintf(BLUETOOTH, final_name);
The problem here:
This function was designed to work with:
int fprintf(FILE *stream, const char *format, …);
so this works perfect and only 8 bytes are sent:
fprintf(BLUETOOTH, "name.txt");
But I need to send a variable size byte array. I was looking for similar functions to fprintf but where you can expecified the lenght of bytes you want to print, but I couldn't find.
Does anyone knows witha format simiar to:
int fprintf(FILE *stream, char *format, int lenght);

You can use fwrite for writing an arbitrary data with a given length into a file (or device file), not only strings.

Related

How to read in a binary file and store the data at a pointer in C

So I am working on a project and I am failing to put all the pieces together to make this work. We need to read in the header of a binary file and store them at the specified pointer.
the function I am working in:
int read_header (FILE *file, elf_hdr_t *hdr);
I understand how to pass the info to the function but I am failing to understand how to read in to the specified pointer. I have been trying to find information on this all day but cant really figure out my starting point... Thanks for any direction you can provide.
My code so far:
int read_header (FILE *file, elf_hdr_t *hdr)
{
int read;
read = fread(hdr, 1, sizeof(hdr), file);
fclose(file);
}
I want to know if I am doing what I am trying here, basically want to read in one byte at a time to the specified pointer.
Since hdr is a pointer, sizeof(hdr) will just be the size of a pointer. You want sizeof(*hdr) or sizeof(elf_hdr_t) to get the size of the elf header struct that the pointer points at...
please re-read the MAN page for fread()
These two parameters: 1, sizeof(hdr), are saying to read in sizeof(hdr) bytes, not to read in 1 byte

Should POSIX `read()`'s `buf` be `signed` or `unsigned`? Does it even matter?

POSIX read function is defined as ssize_t read(int fd, void *buf, size_t count);, taking its buf argument as void*.
Does it matter if the actual buffer passed in is an array of chars or unsigned chars? If so, which one should I use? I googled and read the man, but even the type of the buffer isn't mentioned, let alone its signedness.
The reason for having the declared type void * is that you can read pretty much any type. You can read a char. You can read an unsigned char. You can read an int, if what you wrote to the file earlier was also an int. You can read a struct div_t, if that is what was written to the file.
Pick whatever type was written to the file, or if you're reading arbitrary bytes, whichever type works best for your later processing.
Does it matter if the actual buffer passed in is an array of chars or unsigned chars?
No. Moreover, those are not your only choices. The buffer to which the second argument points can have any object type. It's reasonably common for it to point to either a char array or an unsigned char array, but not so uncommon for it to point to an array of some (other) integer type, or to an object of structure type, or to something else.
The primary objective is to interpret the data received according to the data type intended by the sender, and that requires that you either know in advance or be able to determine from the data what type is intended. In other words, sender and receiver need to agree on some kind of communication protocol.
The simplest possible protocol is an undifferentiated stream of bytes; for that, an unsigned char array is the most appropriate choice. Some other choices are better suited to other protocols.
"read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf."
Read() will store bytes from your file descriptor (be a file, a socket or whatever).
The bytes will be stored at your pointer address, whatever its type. The way your program understand those bytes depends on how you declared it.
so for example, same byte 0xFF may be interpreted as 255 or -1 by your program upon buf declaration
From http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html:
The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.
It is up to you how to interpret the bytes. Whether your buf is an array of char or unsigned char does not make a difference to the workings of read. Only you decide how to interpret the data. If the data contained in the file are not char, you might end up misinterpreting its contents if you treat them as an array of char. That again depends on your platform.
It is not necessarily correct to interpret the data as an array of unsigned char either. The data in the file might be an array of floats or an array of struct containing mixed data types.
Bottom line - you need to read the data into the appropriate object type in memory. To do that, you have to know what is saved in the file.

Receiving rtp packets and writing them into binary file

I am receiving rtp packets from a server that I have to write them into a .mp3 file and I have a few questions on how to complete this task. The last packet I am receiving contains an "END" string.
My code is the following:
int size = 524;
char rtp[size];
FILE *f;
f=fopen("music.mp3","wb");
while(strcmp((char *)rtp, "END")){
recvfromserver(socket,rtp,sizeof(rtp));
fwrite(rtp, sizeof(rtp), 1, f);
}
fclose(f);
My questions are the following:
Is char the correct type for this type of packet? I have to write the file in binary so I do not know if I am doing it right.
How do I write into the file without writing the header of the rap packet? This header is 12B and I should remove it before doing fwrite(), but I do not know if I have to use char or int.
Thanks a lot in advance!
Yes char* is the right data type for your need. In fact I would be more inclined to use unsigned char*
I have done the following modification to your code:-
Initialized the rtp buffer - Think of a case the stack memory where rtp is defined contains "END\0XXX" ? Your write loop will never execute. Always a good practice to initialize variables form stack
Since you are saying you don't need to write the first 12 bytes from rtp, I have advanced the byte pointer by 12 in fwrite
Adjusted the 2nd param of fwrite by 12 bytes to ensure you are not writing form beyond 524 bytes of rtp
You might have to think about what you get from recvfromserver Is that a null terminated character array?
Modified code:-
int size = 524;
char rtp[size] = {0}; //Initialized rtp
FILE *f;
f=fopen("music.mp3","wb");
while(strcmp((char *)rtp, "END")){
recvfromserver(socket,rtp,sizeof(rtp));
fwrite(rtp+12, sizeof(rtp)-12, 1, f); //adjusted for 12 bytes of header
}
fclose(f);

How can I allocate just enough memory for one line of text read from a file in c

The objective of my program that I need to write is that it will read in a line from a file ONLY ONCE (meaning when you read it once you should not go back to the file and read it again), and it should store that line in an array of chars. The size of the array must be just big enough to hold the line of text in. Also, it is recommended to not use getchar, and instead use fgets.
Worst case, there is only one line of text in the file, so you would need to get the file size and allocate that much memory for the buffer.
#include <io.h>
#include <stdlib.h>
long buffLen = _filelength(...);
// check bufLen for errors
char* buffer = (char*)malloc((size_t)buffLen);
// check for allocation failures (it could be an 8 gigabyte file)
If your CRT doesn't support the _filelength posix function, look through this thread, and also keep in mind that a long isn't 64-bits on all platforms, so using a method that returns a 64-bit value is best.
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
//this two function will help you,you can man them on linux
Loop around fget() until NULL is returned and feof() is true or the data read ends with a \n. For each iteration read in the data into a temporary buffer and append it to a final buffer, which is increased in size accordingly.

Accessing values from i2c address

You can take a look at this website: http://www.hitechnic.com/cgi-bin/commerce.cgi?preadd=action&key=NSK1042 to get a better understanding of what I'm talking about. For example, the website reads: the i2c address of the sensor is 0x10 and the table of the values there reads:
Address Type Contents
00 – 07H chars Serial Version Number
43H byte Sensor 1 DC Signal Strength
How can I access these values in C? Thanks.
These registers can be memory mapped. A few things you'll need to do:
map the device's physical memory to your programs address space
declare any pointers to this region as volatile
The volatile keyword will stop the compiler from "optimizing" the program to be incorrect. e.g. by assuming that reads to the same memory location will yield the same result because the program hasn't written to it.
The easy part of this is to declare a struct such that all the offsets are the same as the device and that each part has the right size.
ie
struct hitech {
char serial_version[8];
char manufacturer[8];
/* etc */
};
volatile struct hitech *my_device;
The second part is working out where the device is mapped. If it's plugged in to your computer you should be able to see this. You might need to do one of the following: mmap the device's physical address. Or just write my_device = 0x< address >. Or a combination of the two.
From the website:
"The I2C address of the IRSeeker V2 sensor is 0x10"
So you want to write 0x10 above for my_device.
Then you'll need to compile for the correct micro-controller and load your program at the correct location as firmware.
You'd be better off using their programming language.
Assuming they're not supplying an SDK for you to access these values:
// I'm assuming these are read-only, hence the "const"
const char *g_serialVersionNumber = (const char *)0x00; // be careful not to access more than 8 bytes
const unsigned char *g_sensor1DCSignalStrength = (const unsigned char *)0x43;
void main()
{
printf("Serial version number: %s\n", g_serialVersionNumber);
printf("Sensor 1 DC Signal Strength: %d\n", *g_sensor1DCSignalStrength);
}

Resources