Я новичок в программировании на С ++.У меня есть небольшое упражнение, которое позволяет использовать следующее: использование программирования сокетов Windows, использование оконных API-функций (CreateFile, ReadFile и WriteFile) и использование функций seekg, seekp, tellg и tellp.
Вот что происходит в моем коде:
Откройте файл .txt
с URL-адресами внутри (reddit.com, stackoverflow.com, google.com), а затем прочитайте URL-адреса иположить внутрь strVal
.
Затем я делю значение данных внутри strVal
, используя разделитель ","
, затем цикл начинается.
Затем начнется программирование сокета Windows.
Внутри цикла он получит HTTP-запрос каждого URL-адреса и запросит тип запроса (POST
или * 1024).*).
После получения ответа на запрос данные будут находиться внутри буфера.
Затем я открою *Файл 1033 * для размещения полученного запроса на 3 домена.
Example вот результат output.txt
Результат в порядке, и программа работает над этой частью, но для последнего требования программы они хотят, чтобы я изменилПорядок ответа на данные внутри файла .txt
с использованием seekg, seekp, tellg и tellp.
Я попытался реализовать эти функции, и вот мой код.
fstream fs0 ("C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", ios::in | ios::out | ios::app);
ofstream fs1 ("C:\\Documents and Settings\\Administrator\\My Documents\\output1.txt", ios::out | ios::app);
//1st
fs0.seekg(2020, ios::beg);
char ab[2020];
fs0.read(ab, sizeof(ab));
//2nd
fs0.seekg(0, ios::cur);
char dc[2020];
fs0.read(dc, sizeof(dc));
//3rd
fs0.seekg(0, ios::beg);
char abc[2000];
fs0.read(abc, sizeof(abc));
fs1.write(ab, sizeof(ab));
fs1.write(dc, sizeof(dc));
fs1.write(abc, sizeof(abc));
fs0.close();
fs1.close()
Я только что открыл .txt
файл, в который вставлены данные, затем просто прочитал данные с помощью seekg, затем поместил их в буфер и затем вывел.Нет никакого смысла, потому что если в файл .txt
вставлен еще один домен.
Теперь, моя проблема в этой части.Основываясь на моем коде, как я могу изменить порядок данных внутри txt-файла, используя seekg, seekp, tellg и tellp?
Вот мой общий код,
int main()
{
//getting the data
HANDLE openFile;
//HANDLE openFile1;
HANDLE putdataFile;
BOOL rewriFile;
//BOOL rewriFile1;
char *strVal;
//char *strVal1;
char* point;
//char* point1;
DWORD dwNoBytetoRead = 0;
//DWORD dwNoBytetoRead1 = 0;
DWORD dwNoByteWritten = 0;
char dataextracted[] = "C:\\Documents and Settings\\Administrator\\My Documents";
//40 dash
string dash1 = "\n--------------------";
string dash2 = "--------------------\n";
//connecting to the server
SOCKET Socket;
SOCKADDR_IN SockAddr;
struct hostent *host;
char buffer[10000];
int dataLen;
int i = 0;
//get
string http1 = "GET / HTTP/1.1\r\nHost: ";
string http2 = "\r\nConnection: close\r\n\r\n";
//post
string http3 = "POST / HTTP/1.1\r\nHost: ";
string http4 = "\r\nConnection: close\r\n\r\n";
//winsock startup
WSAData wsaData;
//1 or 2
string input;
//start of program.................................
//open file
openFile = CreateFile(L"C:\\Documents and Settings\\Administrator\\My Documents\\url.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//allocating memory
LARGE_INTEGER fs;
GetFileSizeEx(openFile, &fs);
unsigned long long fSize = fs.QuadPart;
strVal = (char*) malloc (fSize + 1);
memset(strVal, 0, fSize + 1);
//reading the content
rewriFile = ReadFile(openFile, strVal, fSize, &dwNoBytetoRead, NULL);
cout << "The URL/s " << strVal << endl << endl;
CloseHandle(openFile);
//split string
point = strtok(strVal, ",\r\n");
while (point != NULL) {
//get
string httpRequestget = http1 + point + http2;
//post
string httpRequestpost = http3 + point + http4;
//checking kung successful yung wsastartup
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
//connects to domain
Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(point);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
//just to check kung connected or may error pala
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
system("pause");
//return 1;
}else{
cout << "You are now connected to " << point << endl;
}
//choice 1 or 2
cout << "Options to request\n";
cout << "[1] HTTP request using GET\n";
cout << "[2] HTTP request using POST\n";
cout << "Choose an option: ";
cin >> input;
cout << endl;
if (input == "1"){
// Sending a HTTP-GET-Request to the Web Server
int sentBytes = send(Socket, httpRequestget.c_str(), strlen(httpRequestget.c_str()),0);
} else if (input == "2") {
// Sending a HTTP-POST-Request to the Web Server
int sentBytes = send(Socket, httpRequestpost.c_str(), strlen(httpRequestpost.c_str()),0);
}
// Receiving and Displaying an answer from the Web Server
ZeroMemory(buffer, sizeof(buffer));
recv(Socket, buffer, sizeof(buffer), 0);
//put data in a file
putdataFile = CreateFile(L"C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", FILE_APPEND_DATA, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
string dash3 = dash1 + point + dash2;
//write dash
rewriFile = WriteFile(putdataFile, dash3.c_str(), strlen(dash3.c_str()), &dwNoByteWritten, NULL);
//write the content
rewriFile = WriteFile(putdataFile, buffer, 2000, &dwNoByteWritten, NULL);
CloseHandle(putdataFile);
// Cleaning up Windows Socket Dependencies
closesocket(Socket);
WSACleanup();
point = strtok(NULL, ",\r\n");
}
cout << endl << "Data is downloaded here: " << dataextracted << endl << endl;
fstream fs0 ("C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", ios::in | ios::out | ios::app);
ofstream fs1 ("C:\\Documents and Settings\\Administrator\\My Documents\\output1.txt", ios::out | ios::app);
//1st
fs0.seekg(2020, ios::beg);
char ab[2020];
fs0.read(ab, sizeof(ab));
//2nd
fs0.seekg(0, ios::cur);
char dc[2020];
fs0.read(dc, sizeof(dc));
//3rd
fs0.seekg(0, ios::beg);
char abc[2000];
fs0.read(abc, sizeof(abc));
fs1.write(ab, sizeof(ab));
fs1.write(dc, sizeof(dc));
fs1.write(abc, sizeof(abc));
fs0.close();
fs1.close();
system("pause");l
return 0;
}