How to modify a value in textual data file using C - c++

while(!feof(fp))
{
fscanf(fp,"%d %s %d %d",&res[i].id,res[i].title,&res[i].price,&res[i].qty);
i++;
}
while(j<i)
{
printf("\nID:|%d|\tNAME:|%s|\tPRICE:|%d|\tQTY:|%d|",res[j].id,res[j].title,res[j].price,res[j].qty);
j++;
}
I have this piece of code which is collecting data from the file. Now I want to know if get an input from a user like res[id] and I want to decrease the quantity of that particular id how to do that?

If the file is in binary format it is easier to do what you want.
What is the difference between the text and the binary format? If the file is written in binary format, then a 32-bit integer will be represented as 32 consecutive bits in the file. While in text format the number will be represented as sequence of digits for instance 32.
So what's the big deal in that difference? Well if you replace 32 with 1243, in binary format the number will still take the same 32 bits so nothing else needs to be moved, all you change is these 4 bytes. While in the second case you add 2 more digits which will cause all the subsequent contents of the file to shift with two bytes.
In order to shift everything as needed, you will need to read the current contents of the file change the value and then write the contents back. I mean all the contents following the change you are doing.

Related

MIDI Files in Hex Value

I am a beginner in programming
Is there a way to read a midi file in its hex numbers?
I searched the internet that midi files are composed of headers and their contents are in hex numbers like
4D 54 68 64 0A ....
So, what is the best way to extract those hex numbers from a midi file? If there is a C++ library to do this? (I want to write the program in C++ language)
For context, I want to put these hex numbers into an array and replace some of those hex numbers (of course according to the midi file format, so the midi file isn't corrupted) and save it back into a midi file. Like doing some kind of steganography
Let me tell you a secret: There are no hex numbers inside your computer. There are also no decimal numbers. All numbers in your computer are stored as binary. Whenever you write a decimal number like 95 in your code, what C++ does is convert it into binary internally and write it to disk as 1011111.
As such, the problem you're trying to solve needs to be re-phrased. You do not want to read hex numbers, but rather, you want to specify a number as hex in your code (instead of as decimal like usually).
There are various ways to specify a hex number. You could use a calculator to convert the number from hex to decimal, then specify that decimal number in your code (e.g. hex number 4D is 4 * 16 + 13 == 77. So when you've read a number, you can then do if (theNumber == 77) ...).
However, since writing numbers in decimal and hexadecimal is a common thing in programming, C++ actually has a way built in to write hexadecimal numbers. You write your hexadecimal number with a 0x at the start. So to write 77 in hex, you would write 0x4D. So once you've read the number from the file, you would do something like if (theNumber == 0x4D) ....
There are other bases in which you can specify a number in C++. There is 0b for binary numbers (so to specify the number exactly how it will be on disk), and if a number starts with just a 0, C++ thinks it is in octal. So be careful and don't prefix your decimal numbers with zeroes! Because 010 == 8, it's not 10 !
As to actually reading the data from the file, you do that using the fread() function.

How to store the output of huffman coding to a binary file in binary format instead of ASCii format

After encoding a string I've got an output like below from Huffman coding and stored each bit in boolean array.
{00100100100100000000010001000100000101010101010101000010000111}
Now I'm trying to write each bit to .bin file in binary format instead of writing ASCII characters.
However,I read some questions on stack overflow site and many of them were mentioned to use vector or to do some bits shifting operations.I tried first option by storing each bit in a vector,but I cannot figure out a way to write content of vector to a .bin file because it gives an error like this "taking address of temporary -fpermissive".According to the error I've an idea I may messed up dealing with pointers and I don't know much about how bit shifting works.
So,Could someone give me a step by step description or a source code about how to store above output in binary format in a .bin file?For ex: 16 bits store as 2 bytes.I am expecting the answer in c++
Vector<bool> bits;
ofstream data;
data.open("file.bin",ios::out|ios::binary);
size_t size = bits.size();
for (int i=0; i < size; i++)
{
data.write(reinterpret_cast<char*>(&bits[i],sizeof(bool)));
}
data.close();
This is the code I have used to write the content of vector to a binary file.I need above bits array in actual byte not in ascii
Thank you in advance.

convert a string to a sequence of binary

i want to convert any char to its binary representation(not a string like my cuurent code does now) it needs to be a sequence of binary numbers
after that i will take every 16 bits from what i've done and calculate their sum
i cant use numpy or any other package
this is what i got now and it
def checksum(st):
data = ' '.join(map(bin,bytearray(st)))
binar = [data[i:i+16] for i in range(0, len(data), 16)]
check = 0xffff
for hex in binar:
check += int(hex,2)
return check
my current code gets a string (for example:'10100/01') and i want to sum every 16 bits of the string therefor i need to convert the string to binary numbers and then sum every 16 bits together
This answers your question, assuming I understood it properly. The first two lines of your code don't seem to do what you want to achieve, but maybe you just forgot mentioning something.
Anyhow.
def checksum2(st):
dummy = 0xFFFF
for count in xrange(0,len(st),2):
dummy += ord(st[count])+ord(st[count+1])*256
return dummy
This code steps through every second char of your string and adds the value of one char to the value of the next char times 256, which creates a word. Remove the *256 if you didn't actually want to create a proper 16bit value and instead only wanted to add two 8bit values together. And if you rather need a big endian, instead of little endian, then just move the *256 the the other ord().

Data not saved in binary form

I made a program as below
#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<fstream.h>
void main() {
char name[24];
cout << "enter string :";
gets(name);
ofstream fout;
fout.open("bin_data",ios::out|ios::binary);
fout.write((char*)&name,10);
fout.close();
}
But when I open the file bin_data by notepad I find that the string is saved in text format not in binary form...... Please help...
This code can save a word of 10 char.
But when I compile this code by turbo c++ v4.5 I find that. When I input 1 or 2 letter word it saves in text format(ignore garbage value) but when I input a word of 3 to 7 letter long it saves in binary format. and in 9 and 10 letter word again in text format..... Can anyone tell me the reason...?
Please compile and run program as I mentioned above and answer
Your data only contains text. It is represented by the very same bits in both text format and binary format.
Binary format means that your data is written to the file unchanged. If you were to use text format, some non-text characters would be modified. For example, byte 10 (which represents newline) could be changed to operating system specific newline (two bytes, 15 and 10, on Windows).
For binary values of text characters, see http://www.asciitable.com/
Your second example has a buffer overflow.
char name[24];
fout.write((char*)&name,10);
You reserve 24 bytes of data, which is filled by random bytes that happen to be at that point of memory. When you save a 2-character string to the buffer, it only overwrites first three bytes. The third byte is set to value 0, which tells you that the text ends at that point. If you were to call strlen(), it would tell you the amount of characters before the first 0 byte.
If your input is a 2-character text, and you choose to write 10 bytes from your buffer, the 7 bytes in the end are filled with invalid data. Note that this does not cause an access violation, because you have reserved data for 24 bytes.
See also: https://en.wikipedia.org/wiki/Null-terminated_string

issues using stringstream to handle binary file

I'm working with a binary file that I need to grab its useful contents from. The structure is:
Based on a quick look at the file, you don't have an "unknown amt of nulls" anywhere. The format appears to be:
N Bytes: number of animals, integer as text delimited by '\n'
24 Bytes per animal:
16 Bytes: name of animal padded with 0
4 Bytes: some 32 bit number (little endian)
4 Bytes: another 32 bit number (little endian)
You shouldn't be reading this as a text file, but instead as a raw binary file. There's absolutely no need for a stringstream, you can simply parse the number of animals by reading in one byte at a time and adding to the previous value * 10 until you reach '\n'.