so i have this code for checking crc file named map.spak and compare the result with my specified crc result which stored in variable "compare"
int main(int iArg, char *sArg[])
{
char sSourceFile[MAX_PATH];
memset(sSourceFile, 0, sizeof(sSourceFile));
CCRC32 crc32;
crc32.Initialize(); //Only have to do this once.
unsigned int iCRC = 0;
strcpy(sSourceFile, "map.spak");
int compare = 399857339;
ifstream checkfile(sSourceFile);
if (checkfile){
cout << "Checking file " << sSourceFile << "..." << endl;
crc32.FileCRC(sSourceFile, &iCRC);
if(iCRC == compare){
cout << "File " << sSourceFile << " complete!\nCRC Result: " << iCRC << endl;
}else{
cout << "File " << sSourceFile << " incomplete!\nCRC Result: " << iCRC << endl;
}
}else{
cout << "File not found!" << endl;
}
system("pause");
return 0;
}
and now i want to make this code for multiple file
let's say the file name list stored in filelist.txt
the filelist.txt structure:
id|filename|specified crc
1|map.spak|399857339
2|monster.spak|274394072
how to make the crc check, loop for each file name
i'm not really good at c++ i only know some algorithm because i know PHP
c++ is too complicated
this is the full source included CRC source Source Code
or pastebin
TestApp.cpp link
I made several changes to your code. I removed guard headers since we use it only in header files. Old-fasioned memset has been replaced by operation on strings. I suspect that you need to pass char* to CCRC32 object hence sSourceFile is still const char*. I compiled code except parts with CCRC32.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "../CCRC32.H"
int main(int iArg, char *sArg[])
{
std::vector<std::string> filenames;
// TODO - populate filesnames (paths?)
CCRC32 crc32;
crc32.Initialize(); //Only have to do this once.
for (unsigned int i = 0; i < filenames.size(); i++) {
const char* sSourceFile = filenames[i].c_str();
unsigned int iCRC = 0;
int compare = 399857339; // TODO - you need to change this since you are checking several files
std::ifstream checkfile(sSourceFile);
if (checkfile) {
std::cout << "Checking file " << sSourceFile << "..." << std::endl;
crc32.FileCRC(sSourceFile, &iCRC);
if(iCRC == compare){
std::cout << "File " << sSourceFile << " complete!\nCRC Result: " << iCRC << std::endl;
} else {
std::cout << "File " << sSourceFile << " incomplete!\nCRC Result: " << iCRC << std::endl;
}
} else {
std::cout << "File tidak ditemukan!" << std::endl;
}
}
return 0;
}
Related
Okay so a little background this code is supposed to read through a file containing DNA and calculate the number of nucleotides A, C, T, G and print them out and also do some other slight calculations. My code runs fine for most files except for files that contain lines that start with # and + in the file. I need to skip those lines in order to get an accurate number. So my question is how to skip or ignore these lines in my calculations.
My code is
#include <iostream>
#include <stream>
#include <string>
#include <vector>
#include <map>
int main(int argc, char** argv) {
// Ignore how the above argc and argv are used here
auto arguments = std::vector<std::string>(argv, argv + argc);
// "arguments" box has what you wrote on the right side after &&
if (arguments.size() != 2) {
// ensure you wrote a file name after "./a.out"
std::cout << "Please give a file name as argument\n";
return 1;
}
auto file = std::fstream(arguments[1]);
if (!file) {
// ensure the file name you gave is from the available files
std::cout << "Cannot open " << arguments[1] << "\n";
return 1;
}
auto counts = std::map<char,int>({{'G',0.0},{'A',0.0},{'C',0.0},{'T',0.0}});
// Just a test loop to print all lines from the file
for (auto dna = std::string(); std::getline(file, dna); ) {
//std::cout << dna << "\n";
for (auto nucleotide:dna) {
counts[nucleotide]=counts[nucleotide] + 1;
}
}
double total = counts['A'] + counts['T'] + counts['G'] + counts['C'];
double GC = (counts['G'] + counts['C'])*100/total;
double AT = (counts['A'] + counts['T'])*100/total;
double ratio = AT/GC;
auto classification = "";
if ( 40.0 < GC < 60.0) {
classification = "moderate GC content";
}
if (60 <= GC) {
classification = "high GC content";
}
if (GC <= 40.0) {
classification = "low GC content";
}
std::cout << "GC-content: " << GC << "\n";
std::cout << "AT-content: " << AT << "\n";
std::cout << "G count: " << counts['G'] << "\n";
std::cout << "C count: " << counts['C'] << "\n";
std::cout << "A count: " << counts['A'] << "\n";
std::cout << "T count: " << counts['T'] << "\n";
std::cout << "Total count: " << total << "\n";
std::cout << "AT/GC Ratio: " << ratio << "\n";
std::cout << "GC Classification: " << classification << "\n";
}
The file that is giving me trouble is this which is like this
#ERR034677.1 HWI-EAS349_0046:7:1:2144:972#0 length=76
NGATGATAAACAAGAGGGTAAAAAGAAAAAAGCTACAGACATTTCTGCTAATCTATTATTTTGTTCCTTTTTTTTT
+ERR034677.1 HWI-EAS349_0046:7:1:2144:972#0 length=76
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
If anyone can help me with this. I will be very grateful. I only need a hint or an idea of the concept I am missing so I can make my code compatible with all files. Thanks in advance
Your actual problem seems to be the standard case of "input is not always clean syntax".
The solution is always "do not expect clean syntax".
First read whole lines into a buffer.
Then check for syntax.
Skip broken syntax.
Scan clean syntax from buffer.
I would like to use the ftw-function to recursivly traverse a filesystem structure. Additionally, the method shall be used inside of a class. Also, the entry-function, which is called by nftw(), belongs to the same class. That needs to be the case because the entry-function is supposed to change some class-members, dependent on the files that it finds.
When implementing such an approach, I get an error (see below). Is this an issue of syntax or is it not even possible to forward a pointer to a method to nftw()? In case it is not possible, do you know any alternative way to resursivly traverse a filesystem structure under linux?
class model
{
public:
boost::unordered_map<std::string, int> map;
int configure(const char *name)
{
// ...
ftw("DTModels/", this->ftw_entry, 15);
// ...
return = 0;
}
private:
int ftw_entry(const char *filepath, const struct stat *info, const int typeflag)
{
// Here I want to change the member 'map'
std::string filepath_s = filepath;
std::cout << "FTW_Entry: " << filepath_s << std::endl;
}
};
ERROR:
a pointer to a bound function may only be used to call the function
ftw("DTModels/", this->ftw_entry, 15);
I haven't used ftw in many many years and since you ask for an alternative, take a look at std::filesystem (C++17). Many pre-C++17 installations have it available via boost or experimental. If you use one of the pre-C++17 implementations, you many need to remove some of the stat lines from the below to make it work.
#include <iostream>
//#define I_HAVE_BOOST
#if __cplusplus >= 201703L
#include <filesystem>
namespace fs = std::filesystem;
#elif I_HAVE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
auto& out = std::cout;
void show_dent(const fs::directory_entry& dent) {
static size_t indent=0;
std::string ind(indent, ' ');
fs::file_status lstat = dent.symlink_status();
if( fs::is_symlink(lstat) ) {
fs::path pp = fs::read_symlink(dent);
out << ind << dent << " -> " << pp << "\n";
++indent;
show_dent(fs::directory_entry(pp));
--indent;
} else {
if(fs::is_directory(dent)) {
fs::directory_iterator dit_end;
std::cout << "Directory " << dent << " includes the following files:\n";
++indent;
for(auto dit = fs::directory_iterator(dent); dit != dit_end; ++dit) {
show_dent(*dit);
}
--indent;
} else {
fs::file_status stat = dent.status();
out << ind << dent << "\n"
<< ind << " stat\n"
<< ind << " is_regular_file : " << fs::is_regular_file(stat) << "\n"
<< ind << " is_directory : " << fs::is_directory(stat) << "\n"
<< ind << " is_block_file : " << fs::is_block_file(stat) << "\n"
<< ind << " is_character_file: " << fs::is_character_file(stat) << "\n"
<< ind << " is_fifo : " << fs::is_fifo(stat) << "\n"
<< ind << " is_socket : " << fs::is_socket(stat) << "\n"
<< ind << " is_symlink : " << fs::is_symlink(stat) << "\n"
<< ind << " exists : " << fs::exists(stat) << "\n";
if( fs::is_regular_file(stat) ) {
out
<< ind << " file_size : " << fs::file_size(dent) << "\n";
}
}
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv+1, argv+argc);
out << std::boolalpha;
for(const auto& file_or_dir : args) {
show_dent(fs::directory_entry(file_or_dir));
}
return 0;
}
I need to output the 5 largest files from the directory. For this, I use a boost filesystem c++. In the process of writing the program, I encountered difficulties. I can output all files from the directory, file size, file creation date and file attributes. In the vector I put the names of the files, but I just can not figure out how to sort by size. I need to output the 5 largest files from the specified directory. I think that you must first sort by file size by descending. That is, from a larger value to a smaller one. And then the scans are not needed. Most likely it needs to be done in a loop. Help me please.
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
void ShowAttributes(DWORD attributes);
void AttribFile(const char* str);
void Attrib();
int main(int argc, char* argv[])
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
if (argc < 2)
{
cout << "Using Name Directory" << endl;
return 1;
}
path Part(argv[1]);
try
{
if (exists(Part))
{
if (is_regular_file(Part))
{
cout << Part << " Size " << file_size(Part) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
}
else if (is_directory(Part))
{
cout << "Directory " << Part << " include:" << endl;
vector<string> vecList;
for (auto j : directory_iterator(Part))
vecList.push_back(j.path().filename().string());
sort(vecList.begin(), vecList.end());
string filePath;
for (auto i : vecList)
{
cout << " " << i;
filePath = Part.parent_path().string() + "/" + i;
if (is_regular_file(filePath))
{
if (Is_Executable_File(filePath))
cout << "*";
cout << " Size " << file_size(filePath) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
AttribFile(filePath.c_str());
}
cout << endl;
}
}
}
else
cout << Part << " Erroe!" << endl;
}
catch (const filesystem_error& ex)
{
cout << ex.what() << endl;
}
return 0;
}
void ShowAttributes(DWORD attributes)
{
if (attributes & FILE_ATTRIBUTE_ARCHIVE)
cout << " archive" << endl;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
cout << " directory" << endl;
if (attributes & FILE_ATTRIBUTE_HIDDEN)
cout << " hidden" << endl;
if (attributes & FILE_ATTRIBUTE_NORMAL)
cout << " normal" << endl;
if (attributes & FILE_ATTRIBUTE_READONLY)
cout << " read only" << endl;
if (attributes & FILE_ATTRIBUTE_SYSTEM)
cout << " system" << endl;
if (attributes & FILE_ATTRIBUTE_TEMPORARY)
cout << " temporary" << endl;
}
void AttribFile(const char* str)
{
DWORD attributes;
attributes = GetFileAttributesA(str);
ShowAttributes(attributes);
}
void Attrib()
{
char filename[MAX_PATH];
DWORD attributes;
cout << "Name of file: ";
cin >> filename;
attributes = GetFileAttributesA(filename);
ShowAttributes(attributes);
}
create a class or struct to hold the information you need on each file, e.g.
struct MyFile
{
std::string name;
size_t size;
}
create a vector of these and read all files from your folder
then sort the vector and give a custom comparison (e.g. in form of a lambda), see Sorting a vector of custom objects for details on that
Here's a program based on just the standard library that does what you seem to intend:
Live On Coliru
Update: Using C++11 and Boost Filesystem instead: Live On Coliru
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
namespace fs = std::filesystem;
struct tm *last_modified(fs::path const &p) {
auto ftime = fs::last_write_time(p);
auto cftime = decltype(ftime)::clock::to_time_t(ftime);
return std::localtime(&cftime);
}
bool is_executable(fs::path const& p) {
return fs::perms::none != (fs::status(p).permissions() &
(fs::perms::owner_exec |
fs::perms::group_exec |
fs::perms::others_exec));
}
void report(fs::path const& file) {
if (is_executable(file))
std::cout << "*";
std::cout << file << "\tSize:" << fs::file_size(file);
std::cout << "\tModified:" << std::asctime(last_modified(file));
}
template <typename Accessor, typename Cmp = std::less<> >
static auto compare_by(Accessor&& f, Cmp cmp = {}) {
return [f=std::forward<Accessor>(f),cmp](auto const& a, auto const& b) {
return cmp(f(a), f(b));
};
}
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Using: " << argv[0] << " [Name|Directory]" << std::endl;
return 1;
}
fs::path filespec(argv[1]);
try {
if (is_regular_file(filespec)) {
// print
report(filespec);
} else if (is_directory(filespec)) {
std::cout << "Directory " << filespec << " include:" << std::endl;
std::vector<fs::directory_entry> const entries { fs::directory_iterator{filespec}, {} };
// filter just files
std::vector<fs::path> files;
std::remove_copy_if(entries.begin(), entries.end(),
back_inserter(files),
[](auto& de) { return de.is_directory(); });
// get the top 5, or fewer
auto b = files.begin(),
top5 = b + std::min(5ul, files.size()),
e = files.end();
// ordered by size, descending
std::partial_sort(b, top5, e,
compare_by([](auto& p) { return fs::file_size(p); }, std::greater<>{}));
files.erase(top5, e);
// print
for (auto& f : files)
report(f);
} else {
std::cout << filespec << " Error!" << std::endl;
}
} catch (const fs::filesystem_error &ex) {
std::cout << ex.what() << std::endl;
}
}
Prints, e.g. for ./a.out /usr/lib:
Directory "/usr/lib/" include:
"/usr/lib/libruby-1.9.1-static.a" Size:3654748 Modified:Wed Nov 19 21:41:25 2014
"/usr/lib/libruby-1.9.1.so.1.9.1" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libruby-1.9.1.so" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libruby-1.9.1.so.1.9" Size:2087600 Modified:Wed Nov 19 21:41:20 2014
"/usr/lib/libc++.so.1" Size:1460461 Modified:Mon Sep 8 20:01:17 2014
What do I have to do to make my program use a file that has been dragged and dropped onto its icon as a parameter?
My current main method looks like this:
int main(int argc, char* argv[])
{
if (argc != 2) {
cout << "ERROR: Wrong amount of arguments!" << endl;
cout << "\n" << "Programm closed...\n\n" << endl;
exit(1);
return 0;
}
Converter a(argv[1]);
// ...
cout << "\n" << "Programm finished...\n\n" << endl;
// cin.ignore();
return 0;
}
What I'd really like to be able to do is select 10 (or so) files, drop them onto the EXE, and process them from within my application.
EDIT:
The incomming parameter is used as filename, constructed in the cunstructor.
Converter::Converter(char* file) {
// string filename is a global variable
filename = file;
myfile.open(filename.c_str(), ios_base::in);
}
The method where the textfile gets read:
string Converter::readTextFile() {
char c;
string txt = "";
if (myfile.is_open()) {
while (!myfile.eof()) {
myfile.get(c);
txt += c;
}
} else {
error("ERROR: can't open file:", filename.c_str());
}
return txt;
}
EDIT2:
deleted
Update:
I got again to this point.
Actual Main method:
// File path as argument
int main(int argc, char* argv[]) {
if (argc < 2) {
cout
<< "ERROR: Wrong amount of arguments! Give at least one argument ...\n"
<< endl;
cout << "\n" << "Programm closed...\n\n" << endl;
cin.ignore();
exit(1);
return 0;
}
vector<string> files;
for (int g = 1; g < argc; g++) {
string s = argv[g];
string filename = "";
int pos = s.find_last_of("\\", s.size());
if (pos != -1) {
filename = s.substr(pos + 1);
cout << "argv[1] " << argv[1] << endl;
cout << "\n filename: " << filename << "\n pos: " << pos << endl;
files.push_back(filename);
}
files.push_back(s);
}
for (unsigned int k = 0; k < files.size(); k++)
{
cout << "files.at( " << k << " ): " << files.at(k).c_str() << endl;
Converter a(files.at(k).c_str());
a.getATCommandsFromCSV();
}
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
return 0;
}
Actually the console window apears for maybe 0.5 sec and closes again.
It doen't stop on any of my cin.ignore(); Maybe it doesn't get there?
Can anyone help?
Your program does not need to do anything special apart from handling command-line arguments. When you drag-drop a file onto an application in Explorer it does nothing more than to pass the file name as argument to the program. Likewise for multiple files.
If all you expect is a list of file names, then just iterate over all arguments, do whatever you want with them and be done. This will work for zero to almost arbitrarily many arguments.
Maybe you could write a test program like this:
int main(int argc, char* argv[])
{
// argv[0] is not interesting, since it's just your program's path.
for (int i = 1; i < argc, ++i)
cout << "argv[" << i << "] is " << argv[i] << endl;
return 0;
}
And see what happens after you throw different files at it.
EDIT: Just look at Joey's answer.
Answer to the main question
TO SEE THE ANSWER TO YOUR LAST PROBLEM SEE BOTTOM OF THIS ANSWER
All drag&dropped files are get-able as argv[orderOfTheFile] (orderOfTheFile is from 1-n),
however how does windows create that order, now that is a real mystery...
Anyway let's say I would create 26 plain text files ( *.txt ), from a.txt to z.txt on my Desktop,
now if I would drag&dropped them on my ArgsPrinter_c++.exe located directly on C:\ drive,
an output would be similar to this:
argc = 27
argv[0] = C:\ArgsPrinter_c++.exe
argv[1] = C:\Users\MyUserName\Desktop\c.txt
argv[2] = C:\Users\MyUserName\Desktop\d.txt
argv[3] = C:\Users\MyUserName\Desktop\e.txt
argv[4] = C:\Users\MyUserName\Desktop\f.txt
argv[5] = C:\Users\MyUserName\Desktop\g.txt
argv[6] = C:\Users\MyUserName\Desktop\h.txt
argv[7] = C:\Users\MyUserName\Desktop\i.txt
argv[8] = C:\Users\MyUserName\Desktop\j.txt
argv[9] = C:\Users\MyUserName\Desktop\k.txt
argv[10] = C:\Users\MyUserName\Desktop\l.txt
argv[11] = C:\Users\MyUserName\Desktop\m.txt
argv[12] = C:\Users\MyUserName\Desktop\n.txt
argv[13] = C:\Users\MyUserName\Desktop\o.txt
argv[14] = C:\Users\MyUserName\Desktop\p.txt
argv[15] = C:\Users\MyUserName\Desktop\q.txt
argv[16] = C:\Users\MyUserName\Desktop\r.txt
argv[17] = C:\Users\MyUserName\Desktop\s.txt
argv[18] = C:\Users\MyUserName\Desktop\t.txt
argv[19] = C:\Users\MyUserName\Desktop\u.txt
argv[20] = C:\Users\MyUserName\Desktop\v.txt
argv[21] = C:\Users\MyUserName\Desktop\w.txt
argv[22] = C:\Users\MyUserName\Desktop\x.txt
argv[23] = C:\Users\MyUserName\Desktop\y.txt
argv[24] = C:\Users\MyUserName\Desktop\z.txt
argv[25] = C:\Users\MyUserName\Desktop\a.txt
argv[26] = C:\Users\MyUserName\Desktop\b.txt
My ArgsPrinter_c++.exe source code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "argc = " << argc << endl;
for(int i = 0; i < argc; i++)
cout << "argv[" << i << "] = " << argv[i] << endl;
std::cin.ignore();
return 0;
}
Your last problem
I have created a simple program that creates only a sceleton of your class so it can be used, and the program's main itself ran JUST FINE => if your program exits too soon, the problem will be in your class...
Tested source code:
#include <iostream>
#include <vector>
using namespace std;
class Converter{
public:
Converter(const char* f){ cout << f << endl; }
void getATCommandsFromCSV(){ cout << "called getATCommandsFromCSV" << endl; }
};
int main(int argc, char* argv[]) {
vector<string> files;
for (int g = 1; g < argc; g++) {
string s = argv[g];
string filename = "";
int pos = s.find_last_of("\\", s.size());
if (pos != -1) {
filename = s.substr(pos + 1);
cout << "argv[1] " << argv[1] << endl;
cout << "\n filename: " << filename << "\n pos: " << pos << endl;
files.push_back(filename);
}
files.push_back(s);
}
for (unsigned int k = 0; k < files.size(); k++)
{
cout << "files.at( " << k << " ): " << files.at(k).c_str() << endl;
Converter a(files.at(k).c_str());
a.getATCommandsFromCSV();
}
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
return 0;
}
If you go in my post history you'll see that i'm trying to develop an interpreter for a language that i'm working on. I want to use size_t using two different codes, but they all return nothing.
Here is the post of what i was trying: http://stackoverflow.com/questions/1215688/read-something-after-a-word-in-c
When i try to use the file that i'm testing it returns me nothing. Here is the sample file(only a print function that i'm trying to develop in my language):
print "This is a print function that i'm trying to develop in my language"
But remember that this is like print in Python, what the user type into the quotes(" ") is what have to be printed to all, remember that the user can choose what put into the quotes, then don't put something like a simple cout, post something that reads what is inside the quotes and print it to all. But here is the two test codes to do this, but all of they don't returns nothing to me:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
// Error Messages
string extension = argv[ 1 ];
if(argc != 2)
{
cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
return 0;
}
if(extension[extension.length()-3] != '.')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-2] != 't')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-1] != 'r')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
// End of the error messages
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha == "print")
{
size_t idx = linha.find("\""); //find the first quote on the line
while ( idx != string::npos ) {
size_t idx_end = linha.find("\"",idx+1); //end of quote
string quotes;
quotes.assign(linha,idx,idx_end-idx+1);
// do not print the start and end " strings
cout << "quotes:" << quotes.substr(1,quotes.length()-2) << endl;
//check for another quote on the same line
idx = linha.find("\"",idx_end+1);
}
}
}
return 0;
}
The second:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
// Error Messages
string extension = argv[ 1 ];
if(argc != 2)
{
cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
return 0;
}
if(extension[extension.length()-3] != '.')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-2] != 't')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
if(extension[extension.length()-1] != 'r')
{
cout << "Extension not valid!" << endl;
cout << "Default extension *.tr" << endl;
return 0;
}
// End of the error messages
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while (!file.eof())
{
getline(file, linha);
if (linha == "print")
{
string code = " print \" hi \" ";
size_t beg = code.find("\"");
size_t end = code.find("\"", beg+1);
// end-beg-1 = the length of the string between ""
cout << code.substr(beg+1, end-beg-1);
}
}
return 0;
}
And here is what is printed in the console:
ubuntu#ubuntu-laptop:~/Desktop/Tree$ ./tree test.tr
ubuntu#ubuntu-laptop:~/Desktop/Tree$
Like i said, it prints me nothing.
See my post in D.I.C.: http://www.dreamincode.net/forums/showtopic118026.htm
Thanks,
Nathan Paulino Campos
Your problem is the line
if (linha == "print")
which assumes the entire line just read in is "print", not that the line STARTS with print.
Also, why would you use 3 separate checks for a .tr extension, vs. just checking the end of the filename for ".tr"? (You should also be checking that argv[1] is long enough before checking substrings...)
getline(file, linha) will read an entire line from the file, so linha never be equal to print.