Hi I have this script below which streams all the data line by line from input.txt
once that is done the streamed data is then copied to the clipboard.
I want to stream one line process and copy that line, then stream© the next line ...and so on.
E.G:
open input.txt copy first streamed line to clipboard, run mouse click macro, run paste macro
then
copy second streamed line to clipboard, run mouse click macro, run paste macro...
loop this over input.txt
I have already used /n as a deliminator in the iterator stream to separate each line
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
#include <iostream>
#include <sstream>
#include <iterator>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, ss.str());
Sleep(100000);
}
return 0;
}
This line makes your program work on all the lines of the file (now stored as elements in a vector) in one go.
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
To make it work line by line instead, just iterate the elements of the storage vector individually with a for loop.
for (auto str : vecOfStr)
{
toClipboard(hwnd, str);
// run mouse click macro, run paste macro...
}
Related
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
#include <fstream>
#include <vector>
#include <iterator>
using std::cout;
using std::cin;
using std::endl;
using std::string;
std::string FilesOpen(std::string command)
{
const int size_buffer = 2;
char buffer[size_buffer];
memset(buffer, 0, size_buffer * sizeof(char));
std::string result = "";
// Open pipe to file
FILE* pipe = popen(command.c_str(), "r");
if (!pipe)
{
return "popen failed!";
}
// read till end of process:
while (!feof(pipe))
{
// use buffer to read and add to result
if (fgets(buffer, 2, pipe) != NULL)
{
result += buffer;
memset(buffer, 0, size_buffer * sizeof(char));
}
}
pclose(pipe);
return result;
}
int main(int* agrc, char* agrv[])
{
std::vector<std::string> pole;
std::string text;
// get files names and use to ifstream files
FilesOpen("ls /root/workspace/src/server > /root/workspace/filestext.txt");
// get files info size and names
FilesOpen("ls -l /root/workspace/src/server > /root/workspace/filelist.txt");
// get files name and add vector
std::ifstream files;
files.open("/root/workspace/filestext.txt", std::ios_base::in);
if (!files)
{
std::cout << "Error not open files" << std::endl;
}
while (files >> text)
{
pole.push_back(text);
}
files.close();
for (std::vector<std::string>::iterator it = pole.begin(); it != pole.end(); ++it)
{
std::cout << *it << std::endl;
}
// replace text in shell
std::string filereplace = "/root/workspace/testovaci.sh";
std::ofstream r_file(filereplace.c_str());
char patch[] = "patch=";
if (r_file.is_open())
{
for (int i = 0; patch[i] != '\0'; i++)
r_file.put(patch[i]);
r_file.put('D');
}
r_file.close()
}
I need to get the contents of the file name from the filetext.txt file and ignore the folders and list them in the testovaci.sh script, which looks like this:
neco1
neco2
neco3
patch =
neco4
neco5
I need to put in the testovaci.sh file has been added to patch = "file". "file". "file"
and the folders were ignored, leaving only binary files.
Please help me, as I tried everything but nothing works.
I want to print the text files name and contents of a text file in the filepath.
i tried change filepath to c:\temp\ but its error
i tried filtered text file this point in if strchr point
i tried to output txt files content in while loop
How do I fix it?
#define _CRT_SECURE_NO_WARNINGS
#include <io.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filepath = "C:\\TEMP\\*.*"; <- i tried c:\\temp\\ but its error
struct _finddata_t fd;
intptr_t handle;
if ((handle = _findfirst(filepath.c_str(), &fd)) == -1L)
printf("file not fount");
do
{
if (strchr(fd.name,'txt')){ <- i tried filtered text file this point
printf("filename : %s \n", fd.name);
string in_line;
ifstream in(filepath + fd.name); <- i think error this point
while (getline(in, in_line)) {
cout << in_line << "\n"; <-i tried to output txt files content this point
}
in.close();
}
} while (_findnext(handle, &fd) == 0);
_findclose(handle);
return 0;
}
I'm trying to make a small program that will create a Batch file, do something in it and then return a string from it, and after it delete the Batch.
I would like to store the output of the batch file in the variable line.
I tried using getline() but I think it work with .txt files only. I can be wrong.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
ofstream batch;
string line;
batch.open("temp.bat", ios::out);
batch <<"#echo OFF\nwmic os get caption /value\nwmic path win32_videocontroller get description /value\npause\nexit";
batch.close();
system("temp.bat");
remove("temp.bat");
};
In my code I simply using system with my Batch file. I'd like to use cout<<line.
I expect string called line would be equal to the output of the Batch file.
You need to redirect output when using system():
#include <cstdio> // std::remove(const char*)
#include <cstdlib> // std::system(const char*)
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::string foo_bat = "foo.bat";
std::string foo_out = "foo.out";
// Write the batch file
{
std::ofstream f( foo_bat );
f << R"z(
#echo off
wmic os get caption /value
wmic path win32_videocontroller get description /value
)z";
}
// Execute the batch file, redirecting output using the current (narrow) code page
if (!!std::system( (foo_bat + " | find /v \"\" > " + foo_out + " 2> NUL").c_str() ))
{
// (Clean up and complain)
std::remove( foo_bat.c_str() );
std::remove( foo_out.c_str() );
std::cout << "fooey!\n";
return 1;
}
// Read the redirected output file
std::unordered_map <std::string, std::string> env;
{
std::ifstream f( foo_out );
std::string s;
while (getline( f >> std::ws, s ))
{
auto n = s.find( '=' );
if (n != s.npos)
env[ s.substr( 0, n ) ] = s.substr( n+1 );
}
}
// Clean up
std::remove( foo_bat.c_str() );
std::remove( foo_out.c_str() );
// Show the user what we got
for (auto p : env)
std::cout << p.first << " : " << p.second << "\n";
}
WMIC is a problematic program when it comes to controlling the output code page, hence the weird pipe trick we use with system().
But, after all that, you should use the WMI API directly to get this kind of information.
A possible, though admittedly not ideal solution would be to have the batch file write it's output to a .txt file and then read in that file into your program. Look at this SO thread to see how to do this.
Hi my goal is to take each line from input.txt load them into a vector and then copy each vector to the clipboard every 1 second.
So far I am able to load the file into a vector using getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
I am also able to copy a string to the clipboard if I replace:
cout << "Lines Copying " << endl;
with
cout << "Please enter sentence: "; cin >> AAA;
Using the users input...
However, when I try to load the vector called line I get 0 char(s) copied to clipboard?
What am I doing wrong? Any pointers or suggestions will be greatly appreciated..
Using:
Windows 10 64x
Microsoft Visual Studio Community 2015
Version 14.0.23107.0 D14REL
Microsoft .NET Framework
Version 4.7.02046
Visual C++ 2015 00322-20000-00000-AA355
Microsoft Visual C++ 2015
input.txt:
The
Brown
Fox
Jumps
Script:
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
// Print the vector contents.
for (std::string & line : vecOfStr)
std::cout << line << std::endl;
// Copy vector to clipboard.
using namespace std;
string line;
cout << endl;
cout << endl;
cout << "Lines Copying " << endl;
cout << endl;
cout << endl;
cout << "Lines Copied To The Clipboard: ";
cout << endl;
cout << line << endl;
// 1. Strlen takes a const char*, so have to call the strings c_str() method
// (but it would be better to use len = line.length() instead)
size_t len = strlen(line.c_str());
cout << len << " char(s)" << endl;
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, line);
//User input processing.
//cin.clear();
//cin.ignore(255, '\n');
//cin.get();
}
return 0;
}
EDIT:
Updated script
I added a std::ostream_iterator to allow streaming of a vector:
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
Full Updated Script:
Streams content of input.txt and copies all streamed content to clipboard.
// copyfilelines.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <fstream>
#include <string>
#include <vector>
#include <direct.h>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <winuser.h>
#include <cmath>
#include <iomanip>
#include <complex>
#include <iostream>
#include <sstream>
#include <iterator>
void toClipboard(HWND hwnd, const std::string &s);
/*
* It will iterate through all the lines in file and
* put them in given vector then copy vector to clipboard.
*/
//1. Open file and put each line into a vector.
bool getFileContent(std::string fileName, std::vector<std::string> & vecOfStrs)
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid.
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector.
if (str.size() > 0)
vecOfStrs.push_back(str);
}
// Close The File.
in.close();
return true;
}
//2. Declare clipboard functions at file scope.
void toClipboard(HWND hwnd, const std::string &s) {
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
if (!hg) {
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), s.c_str(), s.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
int main()
{
std::vector<std::string> vecOfStr;
// Get the contents of file in a vector.
bool result = getFileContent("input.txt", vecOfStr);
if (result)
{
std::stringstream ss;
// Populate
std::copy(vecOfStr.begin(), vecOfStr.end(), std::ostream_iterator<std::string>(ss, "\n"));
// Display
std::cout << ss.str() << std::endl;
// Copy vector to clipboard.
size_t len = strlen(ss.str().c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, ss.str());
Sleep(100000);
}
return 0;
}
Ignoring all the irrelevant printing to cout, your code is:
if (result)
{
// Copy vector to clipboard.
using namespace std;
string line;
size_t len = strlen(line.c_str());
// Get desktop windows and the call toClipboard.
HWND hwnd = GetDesktopWindow();
toClipboard(hwnd, line);
}
You have a default constructed string called line, and you copy that to the clipboard. Not surprisingly, it contains no characters. I think you need to create a stringstream and print the vector to that, and then copy that to the clipboard.
Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}