When I write to a file, using python open(filename, 'w+'), I get multiple lines of NULL written to the file in addition to the new text. Python 2.7.3
from sys import argv
script, filename, random = argv
my_file = open(filename, 'w+')
added_line = raw_input("Type what you want to add: ")
my_file.write(added_line)
print my_file.read()
my_file.close()
I am teaching myself and practicing opening and writing to files (obviously, I guess). I can get the program to run and prompt me for the new text. I also tried open(filename, 'a').
What am I missing?
Thank you.
I tried opening the file with the w option and as far as I know, if you open the file with w option you are only able to write to file, so you cannot run the read() method. Indeed, w+ enables you to read and write. (Note that 'w+' truncates the file). r+ opens the file for both reading and writing.
my_file.seek(0) return to the top of the file before reading, otherwise you'll just read an empty string.
Worked for me.
Related
I have a txt file that I want to change all characters.
So I'm opening it with this line:
FILE *myFile = fopen(filename, "rb");
The rest of the program uses myFile variable after loaded.
My goal is: crypt this file with another program and decrypt when I load without messing with the rest of the code and keep the original file crypted.
Is there a way?
Is there is a way to read in from a file until the end of a line, then go to another function do something, then come back afterwards to read in from the same file BUT from where we stopped last time (not from the beginning of the file)?
If yes, please provide a snippets. Code makes more sense to me than words. Thanks
When opening a file for writing using std::fstream::open(), you have the options to set the file openmode as the second argument after the filename...
std::fstream file;
file.open("myfile.txt", ios_base::openmode::ate);
openmode::ate is the flag used to open the file with the input cursor positioned at eof.
http://www.cplusplus.com/reference/ios/ios_base/openmode/
http://www.cplusplus.com/reference/fstream/fstream/open/
http://www.cplusplus.com/reference/fstream/fstream/
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.
I'm writing program in C++ (for XAMPP communication) and I want to execute command which I have in strings (I know that this is simply system("command")) but I want to get the output from bash to C++ to string. I've founded several threads about this, but no which solved Bash -> C++.
You can call the FILE *popen(const char *command, const char *mode) function. Then, you can read the file it returns to get the output of your call.
It's like using a pipe to redirect the output of the command you used to a file in the hard drive and then read the file, but you don't get to create a file in the hard drive.
The documentation of the popen() is here.
You need to call the popen function, and read the output from the FILE it returns.
You can try Standard Output Redirection to redirect the standard output to a file stream
and then use it to read to a string.
Dup()