can't read file c++ - c++

There is a file in directory and i'm trying to read a file but i can't. What is wrong with my code. Example is taken from http://www.cplusplus.com/forum/beginner/37208/
#include <iostream>
#include <fstream>
#include <string>
#define MAX_LEN 100
using namespace std;
string inlasning ()
{
string text;
string temp; // Added this line
ifstream file;
file.open ("D:\education\Third course\semestr 2\security\lab1.2\secret_msg.txt");
while (!file.eof())
{
getline (file, temp);
text.append (temp); // Added this line
}
cout << "THE FILE, FOR TESTING:\n" // For testing
<< text << "\n";
file.close();
return text;
}
void main ()
{
inlasning();
}

Change \ to \\ in file path. (or to /)

In string literals \ is used as an escape character.
You have to write \\.
Note: you should check the open call.
On failure, the failbit flag is set (which can be checked with member
fail), and depending on the value set with exceptions an exception may
be thrown.

\ is an escape character, so you need to use \\ to obtain the result you intend.
This is true almost everywhere, even here in stackoverflow where you nee to use it in order to write something like this for example:
*A*
(just put the \ before the *), otherwise (if you don't use the \) stackoverflow will interpret the text and will output an italic A, this:
A
The same is true for bold (two asterisks... two slashes):
**A**
instead of
A
:)
... or maybe you cannot read it because it is a "secret_msg" :P (LOL)

Related

C++ Im trying to stream a file, and replace the first letter of every line streamed. It doesn't seem to be working as expected

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
void add1(std::fstream& files)
{
char c;
int i=0;
int j=0;
int k=0;
int con=0;
string word;
while(files.get(c)&&!files.eof())
{
i++;
j++;
if(c=='\n'||(con>=1&&isspace(c)))
{
con++;
if(con>=2)
{
break;
}
else
{
cout<<j<<"\/"<<i<<endl;
files.seekp(i-j,files.beg);
files.write("h",1);
files.seekg(i);
*seekg ends the loops I tried fstream::clear. I think it would work perfect if seekg worked.
+ without seekg it works but only for 3 lines then its off.
j=0;
word="";
}
}
else
{
con=0;
word=word+c;
}
}
}
*The goal is to be able stream the file, and replace the first letter of every line in the file while streaming.*
You seam to have a logical error and make thinks overcomplicated.
I do not knwow, what you want to do with your variable "word". It is consumed nowhere. So, I will ignore it.
Then you are playing with read and write pointers. That is not necessary. You only need to manipulate the write pointer.
Then, you want to "stream" something. This I do not fully understand. Maybe it means, that you want to write always something to the stream, even, if you do not replace anything. This would in my understanding only make sense, if you would have 2 streams. But in that case it would be brutally simple and no further thinking necessary.
If we use the same stream and do not want to replace a character, then this is already there, existing, and maybe not overwritten by the same character again.
So, if there is nothing to replace, then we will write nothing . . .
Also, and that is very important, we do no replacement operation, if we have an empty line, because then there is nothing to replace. There is now first character in an empty line.
And, most important, we cannot add characters to the same fstream. In that case we would have to shift the rest of the file one to the right. Therefore. 2 streams are always better. Then, this problem would not occur.
So, what's the logic.
Algorithm:
We always look at the previuosly read character. If that was a '\n' and the current character is not, then we are now in a new line and can replace the first character.
That is all.
It will take also into account, if a '\n' is encoded with 2 characters (for example \r\n). It will always work.
And, it is easy to implement. 10 lines of code.
Please see:
#include <iostream>
#include <fstream>
#include <string>
constexpr char ReplacementCharacter{ 'h' };
void replaceFirstCharacterOfLine(std::fstream& fileStream) {
// Here we stor the previously read character. In the beginning, a file always starts
// with a newline. Therefore we pretend that the last read character is a newline
char previouslyReadCharacter{'\n'};
// Here we store the current read character
char currentCharacter{};
// Get characters from file as lon as there are characters, so, until eof
while (fileStream.get(currentCharacter)) {
// No check, if a new line has started. We ignore empty lines!
if ((previouslyReadCharacter == '\n') && (currentCharacter != '\n')) {
// So last charcter was a newline and this is different. So, we are in a new, none empty line
// Set replacement character
currentCharacter = ReplacementCharacter;
// Go one back with the write pointer
fileStream.seekp(-1, std::ios_base::cur);
// Write (an with taht increment file pointer again)
fileStream.put(currentCharacter);
// Write to file
fileStream.flush();
}
else {
// Do not replace the first charcater. So nothing to be done here
}
// Now, set the previouslyReadCharacter to the just read currentCharacter
previouslyReadCharacter = currentCharacter;
}
}
int main() {
const std::string filename{"r:\\replace.txt"};
// Open file
std::fstream fileStream{ filename };
// Check, if file could be opened
if (fileStream)
replaceFirstCharacterOfLine(fileStream);
else
std::cerr << "\n\n*** Error: Could not open file '" << filename << "'\n\n";
return 0;
}

is_open() function in C++ always return 0 value and getLine(myFile, line) does not return anything

Trying to read a file in C++ using fstream.
But the is_open() function always return 0 result and readline() does not read anything. Please see the code snippet below.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("D:\xx\xx\xx\xx\testdata\task1.in.1");
if (myfile.is_open()) {
while (getline(myfile, line)) {
cout << line << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
you think you're opening D:\<somepath>\testdata\task1.in.1
but in fact you're trying to open D:\<somepath><tabulation char>estdata<tabulation char>ask1.in.1 since \t is interpreted as a tabulation.
(like \n is a newline in printf("hello world\n");)
(\x is special too BTW that's not the real path or you would have had another error: error: \x used with no following hex digits which maybe would have talked to you better!)
You have to escape the backslashes like this:
D:\\xx\\xx\\xx\\xx\\testdata\\task1.in.1
Windows also accepts paths like those, more convenient, unless you want to generate batch scripts with cd commands or the like that would require backslashes (/ is used as option switch in batch commands):
D:/xx/xx/xx/xx/testdata/task1.in.1
As NathanOliver stated, you can use the raw prefix if your compiler has C++11 mode enabled (or with --std=c++11)
R"(D:\xx\xx\xx\xx\testdata\task1.in.1)"
Last word: dirty way of getting away with it:
D:\Xx\Xx\Xx\Xx\Testdata\Task1.in.1
Using uppercase in that case would work
because windows is case insensitive
C would let the backslashes as is.
But that's mere luck. A lot of people do that without realizing they're very close to a bug.
BTW a lot of people capitalize windows paths (as seen a lot in this site) because they noticed that their paths wouldn't work with lowercase without knowing why.

c++ read Arabic text from file

In C++, I have a text file that contains Arabic text like:
شكلك بتعرف تقرأ عربي يا ابن الذين
and I want to parse each line of this file into a string and use string functions on it (like substr, length, at...etc.) then print some parts of it to an output file.
I tried doing it but it prints some garbage characters like "\'c7\'e1\'de\'d1\"
Is there any library to support Arabic characters?
edit: just adding the code:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream ip;
ip.open("d.rtf");
if(ip.is_open() != true){
cout<<"open failed"<<endl;
return 0;
}
string l;
while(!ip.eof()){
getline(ip, l);
cout<<l<<endl;
}
return 0;
}
Note: I still need to add some processing code like
if(l == "كلام بالعربي"){
string s = l.substr(0, 4);
cout<<s<<" is what you are looking for"<<endl;
}
You need to find out which text encoding the file is using. For example, to read an UTF-8 file as a wchar_t you can (C++11):
std::wifstream fin("text.txt");
fin.imbue(std::locale("en_US.UTF-8"));
std::wstring line;
std::getline(fin, line);
std::wcout << line << std::endl;
The best way to deal with this, in my opinion, is to use some UNICODE helper. The strings in C or even in C++ are just an array of bytes. When you do, for example, a strlen() [C] or somestring.length() [C++] you will only have the number os bytes of that string instead of number os characters.
Some auxiliar functions can be used help you on it, like mbstowcs(). But my opinion is that they are kinda old and hard to use.
Another way is to use C++11, that, in theory, has support for many things related to UTF-8. But I never saw it working perfectly, at least if you need to be multi-platform.
The best solution I found is to use ICU library. With this I can work on UTF-8 strings easily and with the same "charm" as working with a regular std::string. You have a string class with methods, for length, substrings and so on... and it's very portable. I use it on Window, Mac and Linux.
You can use Qt too .
Simple example :
#include <QDebug>
#include <QTextStream>
#include <QFile>
int main()
{
QFile file("test.txt");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&file);
QString text=stream.readAll();
if(text == "شكلك بتعرف تقرأ عربي يا ابن الذين")
qDebug()<<",,,, ";
}
It is better to process an Arabic text line by line. To get all lines of Arabic text from file, try this
std::wifstream fin("arabictext.txt");
fin.imbue(std::locale("en_US.UTF-8"));
std::wstring line;
std::wstring text;
while ( std::getline(fin, line) )
{
text= text+ line + L"\n";
}

replace and write to file c++

I want write code to find words in a file and replace words.
I open file, next I find word. I have a problem with replace words.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string contain_of_file,a="car";
string::size_type position;
ifstream NewFile;
NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);
position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
NewFile<<contain_of_file.replace(position,5, a );
}
}
NewFile.close();
cin.get();
return 0;
}
How can I improve my code?
lose the using namespace std;
don't declare the variables before needed;
I think the English word you were looking for was content -- but I am not an English-native speaker;
getline already returns NewFile.good() in boolean context;
No need to close NewFile explicitly;
I would change the casing on the NewFile variable;
I don't think you can write to an ifstream, and you ought to manage how you are going to replace the contents of the file...
My version would be like:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
int main() {
std::rename("plik1.txt", "plik1.txt~");
std::ifstream old_file("plik1.txt~");
std::ofstream new_file("plik1.txt");
for( std::string contents_of_file; std::getline(old_file, contents_of_file); ) {
std::string::size_type position = contents_of_file.find("Zuzia");
if( position != std::string::npos )
contents_of_file = contents_of_file.replace(position, 5, "car");
new_file << contents_of_file << '\n';
}
return 0;
}
There are at least two issues with your code:
1. Overwriting text in a file.
2. Writing to an ifstream (the i is for input, not output).
The File object
Imagine a file as many little boxes that contain characters. The boxes are glued front to back in an endless line.
You can take letters out of boxes and put into other boxes, but since they are glued, you can't put new boxes between existing boxes.
Replacing Text
You can replace text in a file as long as the replacement text is the same length as the original text. If the text is too long, you overwrite existing text. If the replacement text is shorter, you have residual text in the file. Not good in either method.
To replace (overwrite) the text, open the file as fstream and use the ios::in and ios::out modes.
Input versus Output
The common technique for replacing text is to open the original file for *i*nput and a new file as *o*utput.
Copy the existing data, up to your target text, to the new file.
Copy the replacement text to the new file.
Copy any remaining text to the new file.
Close all files.

Read File line by line using C++

I am trying to read a file line by line using the code below :
void main()
{
cout << "b";
getGrades("C:\Users\TOUCHMATE\Documents\VS projects\GradeSystem\input.txt");
}
void getGrades(string file){
string buf;
string line;
ifstream in(file);
if (in.fail())
{
cout << "Input file error !!!\n";
return;
}
while(getline(in, line))
{
cout << "read : " << buf << "\n";
}
}
For some reason it keeps returning "input file error!!!". I have tried to full path and relative path (by just using the name of the file as its located in the same folder as the project). what am I doing wrong?
You did not escape the string. Try to change with:
getGrades("C:\\Users\\TOUCHMATE\\Documents\\VS projects\\GradeSystem\\input.txt");
otherwise all the \something are misinterpreted.
As Felice said the '\' is an escape. Thus you need two.
Or you can use the '/' character.
As windows has accepted this as a directory separator for a decade or more now.
getGrades("C:/Users/TOUCHMATE/Documents/VS projects/GradeSystem/input.txt");
This has the advantage that it looks much neater.
first, if you wanna say '\' in a string, you should put '\\', that's the path issue.
then, the string buf is not in connect to your file..
The backslash in C strings is used for escape sequences (e.g. \n is newline, \r carriage return, \t is a tabulation, ...), thus your string is getting garbled because for each backslash+character sequence the compiler is replacing the corresponding escape sequence. To enter backslashes in a C string you have to escape them, using \\:
getGrades("C:\\Users\\TOUCHMATE\\Documents\\VS projects\\GradeSystem\\input.txt");
By the way, it's int main, not void main, and you should return an exit code (usually 0 if everything went fine).