Enable the writing of ANSI escape codes on a file? - c++

I am struggling with a problem. I searched all around the web and StackOverflow website and found similar questions, but none of them provided me the answer I am searching.
I am on a Linux system (Ubuntu) and basically want to know how to write an ANSI escape code in an output file. For example, if I want to write a red string on the terminal I do:
cout << "\033[31m" << "Red string";
and it works. But if I want to write it on a .rtf file for example:
#include <iostream>
#include <fstream>
using namespace std;
ofstream os( "this_file.rtf" );
os << "\033[31m" << "Red string";
os.close();
it doesn't work and output in the file something like:
#[31mRed string
is there a way to enable the writing of an ANSI escape code on an output file like that one? Thanks.

After all your answers and weeks of practice, the solution for this answer is pretty obvious and is the following: file redirection of ANSI escape sequences manipulation depends on the kind of file you are writing in and you have to manually set the way in which you want to translate the ANSI into the output file, depending of course also on the file format you are considering.

Related

Trouble with special characters

First of all, I'm a newbie in programming so you might have to be patient with me. The thing is, I'm writing a program that basically gets input and uses it to output some information plus the inputs in a .doc.
My problem is that I have some constant strings that output in a screwed up way when I use special characters like é í ó ã õ º ª.
I was able to fix it by adding setlocale(LC_ALL, ("portuguese")) but then I screwed my outputs of inputs (aka variable strings) that doesn't print special characters any more. Any clues how i can solve this? I've already tried wstrings and looked everywhere but couldn't find a single solution.
I can show my code here if it helps.
Here is an example of my problem:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
wcout << "Enter special characters like éíó: ";
getline (cin, a);
cout << a;
}
I can't make the constant string and the variable string output correctly in the console at the same time.
You are probably using Windows. The Windows' Command Prompt default encoding is CP850, this encoding is rarely used anywhere else and it will display most special symbols differently from what you usually see in your favorite text editor. You can try to use the Windows APIs SetConsoleOutputCP(1252); and SetConsoleCP(1252); to change to CP1252, an encoding that is somewhat more compatible and should display those symbols the same way you see in the editor. You will need the #include <windows.h>, if its available.

Including files as raw string literals [duplicate]

This question already has answers here:
"#include" a text file in a C program as a char[]
(21 answers)
Closed 9 years ago.
I have a C++ source file and a Python source file. I'd like the C++ source file to be able to use the contents of the Python source file as a big string literal. I could do something like this:
char* python_code = "
#include "script.py"
"
But that won't work because there need to be \'s at the end of each line. I could manually copy and paste in the contents of the Python code and surround each line with quotes and a terminating \n, but that's ugly. Even though the python source is going to effectively be compiled into my C++ app, I'd like to keep it in a separate file because it's more organized and works better with editors (emacs isn't smart enough to recognize that a C string literal is python code and switch to python mode while you're inside it).
Please don't suggest I use PyRun_File, that's what I'm trying to avoid in the first place ;)
The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.
You could preprocess script.py into something like:
"some code\n"
"some more code that will be appended\n"
and #include that, however. Or you can use xxd​ -i to generate a C static array ready for inclusion.
This won't get you all the way there, but it will get you pretty damn close.
Assuming script.py contains this:
print "The current CPU time in seconds is: ", time.clock()
First, wrap it up like this:
STRINGIFY(print "The current CPU time in seconds is: ", time.clock())
Then, just before you include it, do this:
#define STRINGIFY(x) #x
const char * script_py =
#include "script.py"
;
There's probably an even tighter answer than that, but I'm still searching.
The best way to do something like this is to include the file as a resource if your environment/toolset has that capability.
If not (like embedded systems, etc.), you can use a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It'll take a file's binary representation and spit out a C source file that includes an array of bytes initialized to that data. You might need to do some tweaking of the tool or the output file if you want the array to be '\0' terminated.
Incorporate running the bin2c utility into your makefile (or as a pre-build step of whatever you're using to drive your builds). Then just have the file compiled and linked with your application and you have your string (or whatever other image of the file) sitting in a chunk of memory represented by the array.
If you're including a text file as string, one thing you should be aware of is that the line endings might not match what functions expect - this might be another thing you'd want to add to the bin2c utility or you'll want to make sure your code handles whatever line endings are in the file properly. Maybe modify the bin2c utility to have a '-s' switch that indicates you want a text file incorportated as a string so line endings will be normalized and a zero byte will be at the end of the array.
You're going to have to do some of your own processing on the Python code, to deal with any double-quotes, backslashes, trigraphs, and possibly other things, that appear in it. You can at the same time turn newlines into \n (or backslash-escape them) and add the double-quotes on either end. The result will be a header file generated from the Python source file, which you can then #include. Use your build process to automate this, so that you can still edit the Python source as Python.
You could use Cog as part of your build process (to do the preprocessing and to embed the code). I admit that the result of this is probably not ideal, since then you end up seeing the code in both places. But any time I see the "Python," "C++", and "Preprocessor" in closs proximity, I feel it deserves a mention.
Here is how automate the conversion with cmd.exe
------ html2h.bat ------
#echo off
echo const char * html_page = "\
sed "/.*/ s/$/ \\n\\/" ../src/page.html | sed s/\"/\\\x22/g
echo.
echo ";
It was called like
cmd /c "..\Debug\html2h.bat" > "..\debug\src\html.h"
and attached to the code by
#include "../Debug/src/html.h"
printf("%s\n", html_page);
This is quite system-dependent approach but, as most of the people, I disliked the hex dump.
Use fopen, getline, and fclose.

Is it Possible to Display Editable Text In A Shell Via The Standard C++ IOStream?

Is it possible to display interactive and editable text in a console via a standard C++ iostream?
In other words, would it be possible to have basic Vim-esque text editing abilities using only the standard C++ iostream within a shell?
For example, suppose a simple string exampleText containing the text "Example text." was displayed in a shell window using the code:
std::string exampleText = "Example text.";
std::string editedText;
std::cout << exampleText;
would it be possible to edit the string stored in exampleText while it is displayed in a shell and then save the edited version of that string into editedText?
I have doubts about this being possible, but if anyone could help to clarify whether or not this would be possible I would greatly appreciate it.
Thanks in advance!
Of course it is possible. Just output the correct terminal escapes. For each escape make sure you cover for all the popular terminals.
Or save yourself the trouble and use readline or ncurses.

C++ Screen Scraping from HTML

i'm trying to extract the data "Lady Gaga Fame Monster" from the html below using substr and find, but i wasn't able to retrieve the data.
<div class="album-name"><strong>Album</strong> > Lady Gaga Fame Monster</div>
I'm tried to extract the whole string first, but i can only extract till Album under the command cout << line_found , as there's spacing that prevents it from proceeding further.
I try cout << extract_line. I see no spaces in the extracted html code.
I tried the tutorial based from this http://www.cplusplus.com/reference/string/string/substr/, it works, even with spaces. I'm following closely but it stops extracting once it hit spaces. Pls help really appreciated. thanks. Figuring out 2 days without any solution.
here's the source code:
#include "parser.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string line_found, extract_line, result, finalResult="";
int firstPosition, secondPosition, input, location;
ifstream sourceFile ("cd1.htm"); // extracts from sourcefile
while(!sourceFile.eof())
{
sourceFile >> extract_line;
location = extract_line.find("album-name");
// cout << extract_line;
if (location >=0)
{
line_found = extract_line.substr(location);
cout << line_found << endl;
firstPosition= line_found.find_first_of(">");
result = line_found.substr(firstPosition);
}
}
return 0;
}
The >> operator doesn't fetch lines. It fetches whitespace-separated tokens. Use std::getline (see here) instead.
Better still, don't use string searching tools to parse HTML. It's a disaster waiting to happen. In fact, it's happening to you right now. Note that there is more than one instance of > in your line, so you will probably find the wrong one and get yourself in a complete muddle trying to skip all the ones that don't matter (you could try looking for " > ", but what if you encounter this: ...class="album-name" > <strong>..., which is perfectly valid HTML.
If the HTML is proper XHTML, use an XML parser instead. Expat, for instance, is small, fast and (relatively) simple to use. You can find a nice, easy intro here.
If the HTML is messy, you're going to struggle with C++. There's a related SO question here. Alternatively, use a language with a good HTML library such as Python (Beautiful Soup), which you can call from C++.
Another lightweight and simple option could be to use a regex. VS2010 and VS2008 (SP1 IIRC) come with the #include header that should allow much more control and flexibility than your approach.
It wouldn't be as robust as Marcelo's approach but would be quicker to get started with.

Unable to open fstream when specifying an absolute path

I know this is rather laughable, but I can't seem to get simple C++ ofstream code to work. Can you please tell me what could possibly be wrong with the following code:
#include <fstream>
...
ofstream File("C:\temp.txt");
if(File)
File << "lolwtf";
Opening the ofstream fails whenever I specify an absolute path. Relative paths seems to work with no issues. I'm really uncertain as to what the issue is here.
Your path is invalid:
"C:\temp.txt"
The \ is escaping the "t" as a horizontal tab character, so the path value ends up as:
"C: emp.txt"
What you want is:
"C:\\temp.txt"
or
"C:/temp.txt"
Even though Windows people seem to prefer the non-standard '\' character as a path separator, the standard '/' works perfectly and avoids annoying problems like this.
So, my advice is to stick to forward slashes...
std::ofstream File("C:/temp.txt");
The problem is in your string, you are not escaping the backslash.
ofstream File("C:\\temp.txt");