C++ help....working with files

Jumpem

Lifer
Sep 21, 2000
10,757
3
81
I could use a little bit of help for a school project. I am somewhat familiar with C++. I have to write a very simple TCP client that connects to a server program(which we are given) and sends it a file(just a dummy text file). However, I have never done any file manipulation before. I need to know how to select the file(from the same directory the program is in) and be able to send it to the server using sockets. Basically, how do I output a file from my program. Thanks for any help or links that are helpful!

Justin
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Here is some basic C++ code to open & read an ascii file:

#include <fstream.h>
#include <string>
#include <list>

using namespace std;

int main(void)
{
fstream file;

file.open("filename.txt", ios::in);

if(!file)
{
cout << "ERROR: Failed opening file.\n";
return -1;
}

list<string> lines;
string line;

while(!file.eof())
{
getline(file, line);
lines.push_back(line);
}

file.close();

//at this point you have a list of string objects. Each string contains one line from the file
//It's up to you how you send the data via your server.

return 0;
}
 

Jumpem

Lifer
Sep 21, 2000
10,757
3
81
Ergeorge, thanks! I don't think I am supposed to dissect the file though. I think that I can get the sockets set up and the client and server to communicate. I just need to be able to take the file(say dummy.txt) and send it through the client socket all in one piece. At the other end the server will take care of reading it.

One more thing that may make a difference is that our protocol requires a null byte to be appended to the end of the file.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
You still have to read the file somehow to send it through the socket. You might be better off treating it as binary, and just grab chunks instead of individual lines. Or you can read the entire file by changing the line terminator to eof instead of eol in the getline call.
Appending a null at the end of the file is trivial also. For the last line: line += '\0'