C++ Winapi. Read first line from a file, displaying in a textbox - c++

I have recently begun to experiment with winapi in C++. Coming along nicely so far.
I do however having a problem with finding a way to read the first line of a file, and displaying it in a textbox.
After some google searching it seems that some people suggest using winapis functions for this, while other say that using fstream is simpler. I did go the fstream way but i run in to some trouble, probably nothing very difficult but, i cannot find an answer for it!
this is my code:
string line;
ifstream filen ("tid.txt");
if (filen.is_open())
{
getline (filen,line);
cout << line << endl;
filen.close();
}
SetDlgItemText(hwnd, IDC_MAIN_EDIT, line);
This give me this problem from the compiler:
Cannot convert `std::string' to `const CHAR*'
Need somekind of conversion here, but dont know what.
What do you think?

Try this:
SetDlgItemText(hwnd, IDC_MAIN_EDIT, line.c_str());

Related

Writing to a .csv file with C++?

TL;DR I am trying to take a stream of data and make it write to a .csv file. Everything is worked out except the writing part, which I think is simply due to me not referencing the .csv file correctly. But I'm a newbie to this stuff, and can't figure out how to correctly reference it, so I need help.
Hello, and a big thank you in advance to anyone that can help me out with this! Some advance info, my IDE is Xcode, using C++, and I'm using the Myo armband from Thalmic Labs as a device to collect data. There is a program (link for those interested enough to look at it) that is supposed to stream the EMG, accelerometer, gyroscope, and orientation values into a .csv file. I am so close to getting the app to work, but my lack of programming experience has finally caught up to me, and I am stuck on something rather simple. I know that the app can stream the data, as I have been able to make it print the EMG values in the debugging area. I can also get the app to open a .csv file, using this code:
const char *path= "/Users/username/folder/filename";
std::ofstream file(path);
std::string data("data to write to file");
file << data;
But no data ends up being streamed/printed into that file after I end the program. The only thing that I can think might be causing this is that the print function is not correctly referencing this file pathway. I would assume that to be a straightforward thing, but like I said, I am inexperienced, and do not know exactly how to address this. I am not sure what other information is necessary, so I'll just provide everything that I imagine might be helpful.
This is the function structure that is supposed to open the files: (Note: The app is intended to open the file in the same directory as itself)
void openFiles() {
time_t timestamp = std::time(0);
// Open file for EMG log
if (emgFile.is_open())
{
emgFile.close();
}
std::ostringstream emgFileString;
emgFileString << "emg-" << timestamp << ".csv";
emgFile.open(emgFileString.str(), std::ios::out);
emgFile << "timestamp,emg1,emg2,emg3,emg4,emg5,emg6,emg7,emg8" << std::endl;
This is the helper to print accelerometer and gyroscope data (There doesn't appear to be anything like this to print EMG data, but I know it does, so... Watevs):
void printVector(std::ofstream &path, uint64_t timestamp, const myo::Vector3< float > &vector)
{
path << timestamp
<< ',' << vector.x()
<< ',' << vector.y()
<< ',' << vector.z()
<< std::endl;
}
And this is the function structure that utilizes the helper:
void onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel)
{
printVector(accelerometerFile, timestamp, accel);
}
I spoke with a staff member at Thalmic Labs (the guy who made the app actually) and he said it sounded like, unless the app was just totally broken, I was potentially just having problems with the permissions on my computer. There are multiple users on this computer, so that may very well be the case, though I certainly hope not, and I'd still like to try and figure it out one more time before throwing in the towel. Again, thanks to anyone who can be of assistance! :)
My imagination is failing me. Have you tried writing to or reading from ostringstream or istringstream objects? That might be informative. Here's a line that's correct:
std::ofstream outputFile( strOutputFilename.c_str(), std::ios::app );
Note that C++ doesn't have any native support for streaming .csv code, though, you may have to do those conversions yourself. :( Things may work better if you replace the "/"'s by (doubled) "//" 's ...

Program Almost Runs ,Trouble With File Operation

The program almost runs but i am not sure how to make the .txt file for this , its not giving me an error.
the project asks me to:
" File encryption is the science of writing the contents of a file in a secret code. Your encryption program should work like a filter, reading the contents of one file, modifying
the data into a code, and then writing the coded contents out to a second file.
The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple one of your own. For example, you could read the first file one character at a time, and add 10 to the ASCII code of each character before it is written to the second file. "
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
fstream fin, fout;
fin.open("testone.txt", ios::in);
fout.open("encrypted.txt", ios::out);
while (!fin.eof())
{
fin.get(ch);
fout.put(ch + 10);
}
fin.close();
fout.close();
system("pause");
return 0;
}
Read this -
Error LNK1561: entry point must be defined
https://social.msdn.microsoft.com/Forums/vstudio/en-US/e1200aa9-34c7-487c-a87e-0d0368fb3bff/error-lnk1561-entry-point-must-be-definedproblem-in-c?forum=vclanguage
Not up on my Visual C, but you may need #include <cstdlib> to get system
LNK1561 means your main function can't be found. Clearly the main function is present, so this should compile. Follow Beta's suggestion and ensure you can compile and run a trivial program.
Putting Compiling issues aside, This code won't work.
Overarching Problem: You are not checking for any errors along the way, so there is no way for your program to tell if anything has gone wrong.
For example, what if the file didn't open? The while (!fin.eof()) becomes an infinite loop. If the file is not open, you can never read EOF. Trying to use EOF as a loop condition is a bad idea anyway. Definitely read the link in #Steephen's comment.
If you fail to read a character with fin.get(ch); then what? The current code tries to use the character anyway. Bad idea.
Testing a stream is pretty simple. if (!fin) does the job. Read up on how streams work to learn why. Thius simple test doesn't tell you what went wrong, but at least you know something went wrong.
To make things easier, most stream functions return the stream. This lets you chain stream operations together and makes if (!fin.get(ch)) an easy way to tell if get worked.
So your IO loop can be as simple as
while (fin.get(ch) && fout.put(ch + 10))
{
}
If get couldn't get ch for any reason--unopened file, end of file, unreadable file--the while loop exits. Afterwards you can query fin to find out why. If EOF, awesome. If not EOF, the output file's probably wrong.
The same applies to put. If put failed, the loop ends. Test for why and decide if you want to keep the file.
I also recommend dropping a quick test at the end of main to print out a check.
fin.open("encrypted.txt", ios::in);
while (fin.get(ch) && std::cout.put(ch - 10))
{
}
A better test would be to read the character, undo the encryption, and compare against the original input.

Brought a Linux C++ Console Application to a Win32 C++ App using VS2010 and the search function from <algorithm> is no longer working

Just like the title says, I've been working on a fairly large program and have come upon this bug. I'm also open to alternatives for searching a file for a string instead of using . Here is my code narrowed down:
istreambuf_iterator<char> eof;
ifstream fin;
fin.clear();
fin.open(filename.c_str());
if(fin.good()){
//I outputted text to a file to make sure opening the file worked, which it does
}
//term was not found.
if(eof == search(istreambuf_iterator<char>(fin), eof, term.begin(), term.end()){
//PROBLEM: this code always executes even when the string term is in the file.
}
So just to clarify, my program worked correctly in Linux but now that I have it in a win32 app project in vs2010, the application builds just fine but the search function isn't working like it normally did. (What I mean by normal is that the code in the if statement didn't execute because, where as now it always executes.)
NOTE: The file is a .xml file and the string term is simply "administration."
One thing that might or might not be important is to know that filename (filename from the code above) is a XML file I have created in the program myself using the code below. Pretty much I create an identical xml file form the pre-existing one except for it is all lower case and in a new location.
void toLowerFile(string filename, string newloc, string& newfilename){
//variables
ifstream fin;
ofstream fout;
string temp = "/";
newfilename = newloc + temp + newfilename;
//open file to read
fin.open(filename.c_str());
//open file to write
fout.open(newfilename.c_str());
//loop through and read line, lower case, and write
while (fin.good()){
getline (fin,temp);
//write lower case version
toLowerString(temp);
fout << temp << endl;
}
//close files
fout.close();
fin.close();
}
void toLowerString(string& data){
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
I'm afraid your code is invalid - the search algorithm requires forward iterators, but istreambuf_iterator is only an input iterator.
Conceptually that makes sense - the algorithm needs to backtrack on a partial match, but the stream may not support backtracking.
The actual behaviour is undefined - so the implementation is allowed to be helpful and make it seem to work, but doesn't have to.
I think you either need to copy the input, or use a smarter search algorithm (single-pass is possible) or a smarter iterator.
(In an ideal world at least one of the compilers would have warned you about this.)
Generally, with Microsoft's compiler, if your program compiles and links a main() function rather than a wmain() function, everything defaults to char. It would be wchar_t or WCHAR if you have a wmain(). If you have tmain() instead, then you are at the mercy of your compiler/make settings and it's the UNICODE macro that determines which flavor your program uses. But I doubt that char_t/wchar_t mismatch is actually the issue here because I think you would have got an warning or error if all four of the search parameters didn't use the same the same character width.
This is a bit of a guess, but try this:
if(eof == search(istreambuf_iterator<char>(fin.rdbuf()), eof, term.begin(), term.end())

Taking the contents of a vector and placing them in a text file

I'm working on an assignment for my computer science class, its a first year course as I'm a beginner and I am having trouble with a certain part.
A quick explanation of what my assignment does is:
It takes information from a text file and puts it in a vector while the program is running, and you can add names to it or remove names from it, and once you are done you need it to save the information, which means you have to take the information back out of the vector and replace it into the text file.
I haven't learned of a way to take information out of a vector and back into a text-file, I saw that a classmate of mine posted on here a few times but he was pretty much dismissed so he told me to ask the question for myself.
We were given a bit of the coding for our program and honestly I have got no clue on how to make the function take the information back out of the vector and into the text file updated.
What ive included:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
here is the function in which it would save into, any help would be greatly appreciated.
void quit_program(string strFileName, vector<string>&vecThisStudent)
{
//write the body of the function
//Hint: this is the function you should write the vector’s content back to the file.
cout<<"Thanks for using the program. Program terminated"<<endl;
}
As you can see we were even given the hint on what the function was supposed to do, but anyone I have spoken to from the class hasnt had a clue on how to get it done (or they dont like me enough to tell me)
If the entire program is needed, I can post it. It looks almost identical to my classmate who posted earlier, but that is just because we were given the majority of the code and we just had to complete a few different things, and I've just been stuck here for the last 10 hours or so.
My read_file
int read_file(string strFileName, vector<string>&vecThisStudent, fstream &inFile)
{
string strFirstName
string strLastName;
inFile.open(strFileName.c_str(), ios::in | ios::out | ios::app);
while (inFile >> strFirstName >> strLastName)
{
vecThisStudent.push_back(strFirstName + " " + strLastName);
}
return 0;
}
Split the problem into sub-problems. Keep splitting to a smaller pieces till each piece is manageable.
In your case sub-problems I would be comfortable working with are "C++ performing action at program exit", "C++ container serialize", "C++ file IO".
The first one will give you C: Doing something when the program exits, the second - ostream iterator usage in c++, and finally the third one - Writing in file C++.
As a final step you just need to combine all three back together.
And Steve, do not blame your professor or your destiny. Being a good programmer is as hard as being a good surgeon, as hard and as rewarding, but requires quite a bit of dedication to grow from mediocrity to a sharp Swiss Army Knife. At your first job interview you'll see how much worse questions can be than ones asked in these assignments.
Seeing your lack of C++ knowledge, I would REALLY suggest watching some tutorials about C++. If you don't know what a for-loop is/how to use it, you will have MAJOR problems with future assignments.
Here are some great series of tutorial.
There's no such thing are taking the contents of a file (or vector) and placing it automatically into a vector (or file).
But to read or write data, take a look at this page.
The general idea of reading a file is:
Iterate though the file and read each input one by one.
Place that input into a vector
The general idea of outputting data to a file is:
Iterate though the data (ex: every element of that vector)
Output that data (ex: that element).
By iterating, I mean running though the data (usually by a for-loop):
int write_file(string strFileName, vector<string>&vecThisStudent, fstream &outFile)
{
outFile.open(strFileName.c_str(), ios::in | ios::out | ios::app);
for (int i = 0 ; i < vecThisStudent.size() ; i++) {
//Use this line to output to console
cout << vecThisStudent[i] << " \n";
//Use this line to output to file
outFile << vecThisStudent[i] << "\n";
}
}
Use ofstream
http://www.cplusplus.com/reference/fstream/ofstream/
Open File..
Write data using << (http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/)
Close file..
I am not sure what exactly you stuck with..

Read and write image data C++

I've just started learning C++, and I'm working on a program that is supposed to grab an image from the hard disk and then save it as another name. The original image should still remain. I've got it work with text files, because with those I can just do like this:
ifstream fin("C:\\test.txt");
ofstream fout("C:\\new.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout.put(ch);
}
fin.close();
fout.close();
}
But I suppose that it's not like this with images. Do I have to install a lib or something like that to get it work? Or can I "just" use the included libraries? I know I'm not really an expert of C++ so please tell me if I'm totally wrong.
I hope someone can and want to help me! Thanks in advance!
Btw, the image is a .png format.
You can use the std streams but use the ios::binary argument when you open the stream. It's well documented and there is several examples around the internet
You are apparently using MS Windows: Windows distinguishes between "text" and "binary" files by different handling of line separators. For a binary file, you do not want it to translate \n\r to \n on reading. To prevent it, using the ios::binary mode when opening the file, as #Emil tells you.
BTW, you do not have to use \\ in paths under windows. Just use forward slashes:
ifstream fin("C:/test.txt");
This worked even back in WWII using MS-DOS.
If the goal is just to copy a file then CopyFile is probably better choice than doing it manually.
#include <Windows.h>
// ...
BOOL const copySuccess = CopyFile("source.png", "dest.png", failIfExists);
// TODO: handle errors.
If using Windows API is not an option, then copying a file one char at a time like you have done is very inefficient way of doing this. As others have noted, you need to open files as binary to avoid I/O messing with line endings. A simpler and more efficient way than one char at a time is this:
#include <fstream>
// ...
std::ifstream fin("source.png", std::ios::binary);
std::ofstream fout("dest.png", std::ios::binary);
// TODO: handle errors.
fout << fin.rdbuf();