How to write data to a binary file using C - c

I want to write the CAN frames to binary file including the current timestamp and CAN ID followed by 8bytes data frame. I have following in my program,
fwrite("&tm->tm_mon+1", sizeof(tm->tm_mon+1),1,fptr);
fwrite("&tm->tm_mday", sizeof(tm->tm_mday+1),1,fptr);
fwrite("&tm->tm_hour", sizeof(tm->tm_hour+1),1,fptr);
fwrite("&tm->tm_sec", sizeof(tm->tm_sec+1),1,fptr);
fwrite("&frame_rd->can_id", sizeof(frame_rd->can_id),1,fptr);
fwrite("&frame_rd->data", sizeof(frame_rd->data),1,fptr);
Is it right way to do so? Can anyone help me in doing it. Thanks in advance.

A few hints (not a complete solution):
The fact that tm->tm_mon is zero-based and thus requires +1 to make sense as a month number jan...dec, does not mean that you must write sizeof(tm->tm_mon+1).
In the same way, if you want to write its value and take its address, that does not mean you have to add 1. Think what you are doing: to what are you adding this 1??? (just as think about what you were taking the size of.)
And if you want to write this value, then do not mix a function like printf which requires a format string (the f meaning "print formatted") with fwrite (the f meaning File Write). Thus you don't provide a format string with what you want to write, you just provide the address of what needs to be written. And of course without any +1 (what would you be adding this 1 to?)
With these hints I hope you can find your answer. And remember, If nothing helps, Read the Manual!

Related

Difficulties understanding how to take elements from a file and store them in C

I'm working on an assignment that is supposed to go over the basics of reading a file and storing the information from that file. I'm personally new to C and struggling with the lack of a "String" variable.
The file that the program is supposed to work with contains temperature values, but we are supposed to account for "corrupted data". The assignment states:
Every input item read from the file should be treated as a stream of characters (string), you can
use the function atof() to convert a string value into a floating point number (invalid data can be
set to a value lower than the lowest minimum to identify it as corrupt)."
The number of elements in the file is undetermined but an example given is:
37.8, 38.a, 139.1, abc.5, 37.9, 38.8, 40.5, 39.0, 36.9, 39.8
After reading the file we're supposed to allow a user to query these individual entries, but as mentioned if the data entry contains a non-numeric value, we are supposed to state that the specific data entry is corrupted.
Overall, I understand how to functionally write a program that can fulfill those requirements. My issue is not knowing what data structure to use and/or how to store the information to be called upon later.
The closest to an actual string datatype which you find in C is a sequence of chars which is terminated by a '\0' value. That is used for most things which you'd expect to do with strings.
Storing them requires just sufficent memory, as offered by a sufficiently large array of char, or as offered by malloc().
I think the requirements of your assignment would be met by making a char array as buffer, then reading in with fgets(), making sure to not read more than fits into your array and making sure that there is a '\0' at the end.
Then you can use atof() on the content of the array and if it fails do the handling of corrupted input. Though I would prefer sscanf() for its better feedback via separate return value.

am i misunderstanding this~ Why is COPY changing the output? (PGPLSQL)

I'm very close to solving a big problem that i'm having at the moment and this is the last bit. I just don't know why the output is different to what's in the database when i need it EXACTLY the same.
Reading the data before entering the database:
[NULL][NULL][NULL][SO][etc.......]
Reading the data from COPY to text file:
\\000\\000\\000\\016[etc...} (it matches, basically)
Reading the data after COPY using binary format
PGCOPY
ÿ
[NULL][NULL][NULL][EOT][etc.......] (first line changes a fair bit)
(rest of the data stays exactly the same.)
˜ÿÿ
The postgresql query being run for test's sake:
COPY (SELECT byteacolumn FROM tablename WHERE id = 1) TO 'C:\path\file' (format:Binary);
So using the binary format gives me almost what i need but not quite. I could botch to ignore the added lines, but i wouldn't know what the first line of data should be.
TL;DR: COPY is adding lines and changing the first row of my data. How do i make it stop? :(
The binary COPY format is really only designed to be consumed by a COPY FROM command, so it contains a lot of metadata to allow Postgres to interpret it.
After the first two lines, the next 9 bytes are also part of the header. The next 2 bytes give the number of fields in the following record, and the next 4 bytes give the number of bytes in the following field. Only then does the actual data begin.
The full details of the format can be found in the documentation, but be aware that they could change in a future release.
(However, assuming this is the same problem you were asking about here, I think this is the wrong way to go about it. You were on the right track with lo_import/lo_export.)

How to take numbers and words out of a txt file and assign them to int and char*

I am making a text based game and want the user to be able to save. When they save all the variables will be saved to a text file.
I can't figure out how to take them out of the file and assigning them to specific variables and pointers.
The file will look somewhat like this:
jesse
hello
yes
rifle
0
1
3
20
Is there anyway I can specify what line I want to take out with fscanf? Or do I have to take a different approach?
There is no way to specify what line to read from because the concept of a file stream in C does not explicitly distinguish new lines. They are simply treated as a character. To read from a specific line, you would have to loop forward with fseek and fgetc until you find '\n' at which point you can update some variable that holds the current line number the stream points to.
One way around this would be to have information at a fixed offset. For example, say you are storing player information then if you make player information a fixed size X and have the constituent data at fixed indexes into each structure, you can just fseek to the right location straight away.
However, if you have structured data, it may be more suitable to use a format which is able to represent these structures inherently such as XML or JSON.
Altough I can't exactly tell what you want, I'd do a few suggestions:
Use a SQLite file instead of a text file. This way you can use SQL to get exactly what you want. Shortcut for you: http://www.sqlite.org/
If you still want to use a text file, use it comma-separated instead of spaces-separated. It's more common of a practice.
I have created a simple settings reader for my C program, maybe it might be useful to you to know how to parse test files
https://codereview.stackexchange.com/questions/8620/coding-style-in-c

How can I parse text input and convert strings to integers?

I have a file input, in which i have the following data.
1 1Apple 2Orange 10Kiwi
2 30Apple 4Orange 1Kiwi
and so on. I have to read this data from file and work on it but i dont know how to retrieve the data. I want to store 1(of 1 apple) as integer and then Apple as a string.
I thought of reading the whole 1Apple as a string. and then doing something with the stoi function.
Or I could read the whole thing character by character and then if the ascii value of that character lies b/w 48 to 57 then i will combine that as an integer and save the rest as string? Which one shall I do? Also how do I check what is the ASCII value of the char. (shall I convert the char to int and then compare, or is there any inbuilt function?)
How about using the fscanf() function if and only if your input pattern is not going to change. Otherwise you should probably use fgets() and perform checks if you want to separate the number from the string such as you suggested.
There is one easy right way to do this with standard C library facilities, one rather more difficult right way, and a whole lot of wrong ways. This is the easy right way:
Read an entire line into a char[] buffer using fgets.
Extract numbers from this line using strtol or strtoul.
It is very important to understand why the easier-looking alternatives (*scanf and atoi) should never be used. You might write less code initially, but once you start thinking about how to handle even slightly malformed input, you will discover that you should have used strtol.
The "rather more difficult right way" is to use lex and yacc. They are much more complicated but also much more powerful. You shouldn't need them for this problem.

How do I accept only the numeric values from a file in C?

I have taken up a project and I would like some help. Basically it is a program to check whether some pins are connected or not on a board.
(Well, that's the simplified version. The whole thing is a circuit with a microcontroller.)
The problem is that, when a pin is connected I get a numeric value, and when it's not connected, I get no value, as in it's a blank in my table.
How can I accept these values?
I need to accept even the blank, to know that its not connected,
plus the table contains some other non-numeric values as well.
I tried reading the file using the fscanf() function but it didn't quite work. I'm aware of only fscanf(), fread(), fgets() and fgetc() functions to read from different kinds of files.
Also, is it possible to read data from an Excel file using C?
An example of the table is:
FROM TO
1 39
2
Over here, the numbers 1 and 2 are under the column FROM and it tells which pin the first end of the connector is connected to. The numbers under TO tell us which pin the other end of the connector is connected to, and when the column is blank, it's not connected at one end.
Now what I'm trying to do is create a program to create an assembly language program for the micro controller, so I need to be able to read whether the connector is connected, and if it is then to which pin? And accordingly, I need to perform some operations. (Which I can manage by myself).
The difficulty I'm facing is reading from a specific line and reading the blank.
Read the lines using fgets() or a relative. Then use sscanf() on the line, checking to see whether there were one or two successful conversions (the return value). If there's one conversion, the second value was empty or missing; if two, then you have both numbers safely.
Note that fscanf() and relatives will read past newlines unless you're careful, so they do not provide the information you need.
so your file is more like this
Col1 col2 \n
r1val1 r1val2\n
.
.
and so on,if this is the case then use fscanf() to read the string (until \n)from the file.Then use strtok() function to break the string into tokens ,here is the tutorial of the same
http://www.gnu.org/s/hello/manual/libc/Finding-Tokens-in-a-String.html
hope this helps...
one more humble suggestion..just work on c programming first if you are a newbie,don't directly go for microcontrollers,as there are lots of things that you might understand in a wrong way if you dont know some of the basic concepts...
This is a common problem in C. When line boundaries carry meaning in the grammar, it's difficult to directly read the file using only the scanf()-family functions.
Just read each line with fgets(3) and then run sscanf() on one line at a time. By doing this you won't incorrectly jump ahead to read the next line's first column.
Since there are two values on a line you can parse the first, find the next whitespace, then parse the next looking for it's absence as well. I say parse rather than scanf() as when I really want control, or have a huge volume of numbers to scan, I use calls in the strtol() family.

Resources