i'm studing on file operations (c++) and i came to a deadlock
i can read datas from a file but i want to put some rules. for example my .txt file is:
<play
**guitar = "false"
**clarinet = "true"
>
<clairnet
**color = "black"
**type = "g"
>
i want to reach clarinet.color and may be change later. i wrote too long codes, i can reach it now. (reading the file character by character and searching for "clarinet" first, when it found it, it start to search color from the "clarinet" line. when it sees color start to search for "=" then gets all the line since = and strtok by ""s.)
it's hard for the hardware and me :')
and the main problem is changing the value. i copy all file except the value, change the value and write all to the file again.
i need to save all datas like a class to the file, like using mysql with php.
how can i do it?
Use serialization. For example: http://www.boost.org/doc/libs/1_58_0/libs/serialization/doc/index.html
Related
In C++ I have made a program which writes given data into a text file (notepad). The problem is when I restart my program and enter other data then it clears the previous one and adds new data.
I want to keep my previous data safe, and add new data in a new line in text file.
For example,
I wrote "I am a programmer" in my program.
Now my text file will show this:I am a programmer
Now if I restart my program and write "I am unemployed". Then textfile shows this: I am unemployed.
But I want my file to be:
I am a programmer
I am unemployed
Please, Help...
You need to open the file with the append flag. If you're using fstream, it looks something like this:
#include<fstream>
using namespace std;
fstream outfile = fstream("myfilename.txt", ios_base::app)
See reference http://www.cplusplus.com/reference/fstream/fstream/open/
So, I want my program to read data from a file, and save it into different quarter1, quarter2,quarter3, quarter4 depending of it's date, but it doesn't seem to work properly and still don't know why, I've been trying to debug and I'm pretty sure it fails when saving at saveQuarters or existeix which is basically a dichothomic search which returns if the code exists and if it exists, it returns the position. This is the code:
I just skimmed through some of the stuff you had so this suggestion may not work, but you can try declaring your file as input or output. Perhaps that could be the problem.
Some thing like:
string fileName = "data.txt";
ifstream dataFile;
dataFile.open(fileName, ios::in);
Doing this:
fitxerCens >> taulaCens[i].stateName;
Will grab an entire line of the data file until it sees a space is correct.
I'm fairly new to Python, so I haven't done much in the way of reading files.
My question is this: if I use
with open(sendFile, 'r') as fileContent:
response = fileContent.read()
will the whole file always be read in to response at once or is there any chance that I'd have to call read() multiple times? Or does read() just handle that case for you?
I believe the file will be closed after this call, so I just want to make sure that I'm getting the whole file and not having to go back, open it again, and read more
Unless you specify a size, the read method reads the whole contents of the file.
From https://docs.python.org/2/library/stdtypes.html#file.read :
If the size argument is negative or omitted, read all data until EOF is reached.
I have a data file data.txt which includes character and numeric data.
Usually I read the data.txt in my program by using file streams like
ifstream infile("C:\\data.txt",ios::in); then use infile.getline to read the values.
Is it anyway possible to have the data.txt file included to the project and compile
it with the project such that when I read the file I do not have to worry about the path
of the file ( I mean I just use something like ifstream infile("data.txt",ios::in) ).
Moreover if I can compile the file with my project I will not have to worry about
providing a separate data.txt file with my release build to anyone else who wants to use
my program.
I do not want to change the data.txt file to some kind of header file. I want to keep the
.txt file as is and somehow package it within my executable that I am building. I still
want to keep using ifstream infile("data.txt",ios::in) and read the lines from the file
but want data.txt file to be with the project just like anyother .h or .cpp files.
I am using C++ visual studio 2010.
It would be kind of someone to provide some insight into the above thing I am trying to
do.
Update
I managed to use the code below to read in the data file as resource
HRSRC hRes = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_TEXT1), _T("TEXT"));
DWORD dwSize = SizeofResource(GetModuleHandle(NULL), hRes); HGLOBAL hGlob = LoadResource(GetModuleHandle(NULL), hRes);
const BYTE* pData = reinterpret_cast<const BYTE*>(::LockResource(hGlob));
but how do I read the separate lines ? Somehow I am unable to read the separate lines. I can't seem to differentiate one line from another.
I can just give you a workaround, if you don't want to worry about the path of the file, you can just:
- add you file to your project
- add a post building event to copy your data.txt file in your build folder.
There was a similar question, that also required inclusion of external file into C++ code. Please check my answer here.
Another way is to include a custom resource in your project, and then use FindResource, LoadResource, LockResource to access it.
You can put the contents of the file in std::string variable:
std::string data_txt = "";
Then use sscanf or stringstream from STL to parse the contents.
One more thing - you will need to handle special characters like '"' by using \ character before each one.
For any kind of file, base on RBerteig anwser you could do something simple as this with python:
This program will generate a text.txt.c file that can be compiled and linked to your code, to embed any text or binary file directly to your exe and read it directly from a variable:
import struct; # Needed to convert string to byte
f = open("text.txt","rb") # Open the file in read binary mode
s = "unsigned char text_txt_data[] = {"
b = f.read(1) # Read one byte from the stream
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
while b != "":
s = s + "," # Add a coma to separate the array
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
s = s + "};" # Close the bracktes
f.close() # Close the file
# Write the resultan code to a file that can be compiled
fw = open("text.txt.c","w");
fw.write(s);
fw.close();
Will generate something like
unsigned char text_txt_data[] = {0x52,0x61,0x6e,0x64,0x6f,0x6d,0x20,0x6e,0x75...
You can latter use your data in another c file using the variable with a code like this:
extern unsigned char text_txt_data[];
Right now I cant think of two ways to converting it to readable text. Using memory streams or converting it to a c-string.
I would like to embed a text file with some data into my program.
let's call it "data.txt".
This text file is usually loaded with a function which requires the text file's file name as input and is eventually opened using a fopen() call... some something to the lines of
FILE* name = fopen("data.txt");
I can't really change this function and I would like the routine to open this same file every time it runs. I've seen people ask about embedding the file as a header but it seems that I wouldn't be able to call fopen() on a file that I embed into the header.
So my question is: is there a way to embed a text file as a callable file/variable to fopen()?
I am using VS2008.
Yes and No. The easiest way is to transform the content of the text file into an initialized array.
char data_txt[] = {
'd','a','t','a',' ','g','o','e','s',' ','h','e','r','e', //....
};
This transformation is easily done with a small perl script or even a small C program. You then compile and link the resulting module into your program.
An old trick to make this easier to manage with a Makefile is to make the script transform its data into the body of the initializer and write it to a file without the surrounding variable declaration or even the curly braces. If data.txt is transformed to data.inc, then it is used like so:
char data_txt[] = {
#include "data.inc"
};
Update
On many platforms, it is possible to append arbitrary data to the executable file itself. The trick then is to find it at run time. On platforms where this is possible, there will be file header information for the executable that indicates the length of the executable image. That can be used to compute an offset to use with fseek() after you have opened the executable file for reading. That is harder to do in a portable way, since it may not even be possible to learn the actual file name of your executable image at run time in a portable way. (Hint, argv[0] is not required to point to the actual program.)
If you cannot avoid the call to fopen(), then you can still use this trick to keep a copy of the content of data.txt, and put it back in a file at run time. You could even be clever and only write the file if it is missing....
If you can drop the call to fopen() but still need a FILE * pointing at the data, then this is likely possible if you are willing to play fast and loose with your C runtime library's implementation of stdio. In the GNU version of libc, functions like sprintf() and sscanf() are actually implemented by creating a "real enough" FILE * that can be passed to a common implementation (vfprintf() and vfscanf(), IIRC). That faked FILE is marked as buffered, and points its buffer to the users's buffer. Some magic is used to make sure the rest of stdio doesn't do anything stupid.
For any kind of file, base on RBerteig anwser you could do something simple as this with python:
This program will generate a text.txt.c file that can be compiled and linked to your code, to embed any text or binary file directly to your exe and read it directly from a variable:
import struct; # Needed to convert string to byte
f = open("text.txt","rb") # Open the file in read binary mode
s = "unsigned char text_txt_data[] = {"
b = f.read(1) # Read one byte from the stream
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
while b != "":
s = s + "," # Add a coma to separate the array
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
s = s + "};" # Close the bracktes
f.close() # Close the file
# Write the resultan code to a file that can be compiled
fw = open("text.txt.c","w");
fw.write(s);
fw.close();
Will generate something like
unsigned char text_txt_data[] = {0x52,0x61,0x6e,0x64,0x6f,0x6d,0x20,0x6e,0x75...
You can latter use your data in another c file using the variable with a code like this:
extern unsigned char text_txt_data[];
Right now I cant think of two ways to converting it to readable text. Using memory streams or converting it to a c-string.