How do I print the content of a file? - c++

How can I print the contents of a file, the name of which is specified via my program's command line?
I do not know how to give the name of file by command line and how to work with it.
For ex this is does not work:
int main(int argc, char *argv[])
{
FILE *f;
char s[20];
cin >> s;
f=fopen_s(s,"rt");
std::cout << f;
_getch();
return 0;
}
error C2660

#include <iostream>
#include <fstream>
int main(int argc , char *argv[])
{
if(argc < 2)
{
std::cout << " Wrong usage " << std::endl;
exit(0);
}
std::string file_name = argv[1];
std::ifstream fs;
fs.open(file_name.c_str());
std::cout << file_name << std::endl;
std::string line ;
while(fs >> line)
{
std::cout << line << std::endl;
}
return 0;
}

You cannot use << operator with char[]
Solution : You can use std::string
std::string s;
Use the string's c_str() value as name in fopen_s(name, "rt")
Solution : You need to put the file in the same directory as the executable
f = fopen_s(s.c_str(), "rt");
You cannot cout << FILE *f
Solution : read file content line by line as you print each line
char* line; //used to receive data for each line
int length; //used to represent how many characters have received
while ((getline(&line, &length, f) != -1) {
print("%s", line);
}

Related

Segmentation fault: unable to fix the problem

I'm new to C++, and I'm trying to write a project that interacts through command line. Right now, whenever I run my main (which is the executable), I always receive a segmentation fault error when the main program finished.
Edit comment:
I'm told by tutor to use as little as C++ features such as vectors or strings ... I'm also very new to C++, so i'm trying to utilize as many basic C functions as I can.
I'm
My main function looks like this:
int main(int argc, char** argv) {
cout << "starting mvote..." << endl;
int run_flag = 1;
char* actionBuffer = (char*)malloc(100 * sizeof(char));
char* action = (char*)malloc(16 * sizeof(char));
char* readPtr;
char exit[4] = { 'e','x','i','t' };
//parse command line argumentand get the filename
char* filename = argv[2];
cout << filename;
FILE* fp;
char line[64];
//from here, I'm opening the file and read it by lines
fp = fopen(filename, "r");
if (fp == NULL) {
cout << "file not exists";
return -1;
}
while (fgets(line, 64, fp) != NULL) {
cout << line << "\n";
}
fclose(fp);
while (run_flag == 1) {
cout << "what do you want?\n " << endl;
cin.getline(actionBuffer, 1024);
if (strcmp(actionBuffer, exit) == 0) {
cout << "bye!";
run_flag = 0;
break;
}
//if not exit, Look for the space in the input
readPtr = strchr(actionBuffer, ' ');
int size = readPtr - actionBuffer;
//extract the operation
strncpy(action, actionBuffer, size);
for (int i = 0; i < size; i++) {
cout << "operation:" << action[i];
}
// depend on the operation specified before the first empty space
run_flag = 0;
}
free(actionBuffer);
free(action);
return 0;
}
Description:
I first try to open up a csv file which lies in the same folder as main, and I read the file line by line. Then, I just implement a simple command where you can type exit and quit the program.
I allocate two memory, actionBuffer and action, which are used to hold command
Problem: a segmentation fault [core dumped] always exists when I type exit and hit enter, and then the process finished.
Research: So I learned that segmentation fault is due to accessing a memory that does not belongs to me. But where in my program am I trying to access such a memory?
Any advice is appreciated! Thank you.
Just to give you an idea, this would be an example of C++ code
#include<iostream>
#include<fstream>
#include<string_view>
#include<string>
#include<sstream>
#include<exception>
int main(int argc, char** argv) {
std::cout << "starting mvote...\n";
//parse command line argumentand get the filename
std::string filename = argv[2]; // NO CHECKS!
std::cout << filename <<'\n';
//from here, I'm opening the file and read it by lines
{
std::ifstream ifs(filename);
if (!ifs) {
throw std::invalid_argument("file not exists");
}
std::string line;
while (std::getline(ifs, line)) {
std::cout << line << '\n';
}
}
bool run_flag = true;
while (run_flag) {
std::cout << "what do you want?\n";
std::string userInput;
std::getline(std::cin, userInput);
if (userInput == "exit") {
std::cout << "bye!\n";
return 0;
}
std::stringstream userInputSs(userInput);
std::string operation;
while(userInputSs >> operation){
std::cout << "operation: " << operation << '\n';
}
}
}

Problem with getting text from a .txt file in c++ using fstream

And thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
string lines[100];
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
lines[0] = line;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
cout << lines[0];
myfile.close();
return 0;
}
And the output is: Writing this to a file.Program ended with exit code: 0
But in my CodeHere.txt it has: hello
I tried saving it, but the result didn't change. I'm not sure whats going on. Can anyone help?
Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.
This should work, using a vector<string> to store the lines read from file
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
vector<string> lines;
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is_open())
{
while ( getline(myfile, line) )
{
lines.push_back(line);
i++;
}
myfile.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << lines[0] << '\n';
return 0;
}
Try this:
vector<string> lines;
if (file.is_open()) {
// read all lines from the file
std::string line;
while (getline(file, line)) {
lines.emplace_back(line);
}
file.close();
}
else {
cout << "Unable to open file";
return -1;
}
cout << "file has " << lines.size() << " lines." << endl;
for (auto l : lines) {
cout << l << endl;
}

Read multiple files by passing them in argv[1]

This might be a basic question, but I am new to C++, so I would appreciate your understanding.
What I am trying to do is to read files from a folder and pass one of them at a time in argv[1], get some results from that file, write them in an output file specified in argv[2], then the same for the next file, and so on.
I guess it has something to do with pointers but I am not sure how to fix this.
Thank you for any input!
Here is what I have so far:
vector<string> getFilenames(string folder)
{
vector<string> names;
string search_path = folder + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
names.push_back(fd.cFileName);
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
int main(int argc, char **argv) {
ofstream fileout(argv[2], ios::out | ios::app);
int a, b, c;
vector<string> filenames = getFilenames("folder path");
istringstream iss;
for (int i = 0; i < filenames.size(); i++) {
iss.str(filenames[i]);
iss >> argv[1];
if (readFile(a, b, c, argv[1]) == 0) {
/* do something */
}
}
fileout.close();
return 0;
}
I want to complete #Florian Klemme but I cannot comment.
There is a little example of how to iterate through command line parameters :
int main(int argc, char **argv)
{
for (auto i = int{0}; i < argc; ++i) {
// do something with argv[i];
}
}
I'm not exactly sure what your problem is but maybe this little example can help as a starting point. It shows how you can
Iterate though files in a directory (you need C++17 though)
Read some number from a file
Write to another file
Hopefully you can add the rest with no problem. :)
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
namespace fs = std::filesystem;
int main(int argc, char **argv) {
std::string input_dir = argv[1];
std::string output_file = argv[2];
std::ofstream out(output_file);
// Iterate over files in directory
for(auto& file : fs::directory_iterator(input_dir)) {
std::ifstream in(file.path());
// In this example, read a integer number from the current file
if (int i; in >> i) {
std::cout << "Read " << i << " from " << file << std::endl;
// ... and write it to the output file.
out << i << std::endl;
}
}
}

Passing a file into a function

I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.
#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
int num_of_lines(ifstream file)
{
int cnt3;
string str;
while(getline(file, str))cnt3++;
return(cnt3);
}
int main(int argc, char **argv)
{
int num_of_lines(ifstream file);
string file;
file = argv[1];
if(argc == 1)die("usage: mywc your_file"); //for some reason not working
ifstream ifs;
ifs.open(file);
if(ifs.is_open())
{
int a;
cout << "File was opened\n";
a = num_of_lines(file);
cout <<"Lines: " << a << endl;
}
else
{
cerr <<"Could not open: " << file << endl;
exit(1);
}
ifs.close();
return(0);
}
Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.
int num_of_lines( ifstream &file )
{
int cnt3 = 0;
string str;
while( getline(file, str) ) cnt3++;
return cnt3;
}
The other thing is you're passing file to it (which is a string) instead of ifs. Change the call to:
a = num_of_lines( ifs );

Enter File Name When Executing Program In C++

I'm learning C++, then i was searching for some codes for learn something in the area that i love: File I/O, but i want to know how i can tweak my code for the user type the file that he wants to see, like in wget, but with my program like this:
C:\> FileSize test.txt
The code of my program is here:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
Thanks!
In the example below argv contains command line arguments as null terminated string array and argc contains an integer telling you how many arguments where passed.
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
long begin,end;
if( argc < 2 )
{
cout << "No file was passed. Usage: myprog.exe filetotest.txt";
return 1;
}
ifstream myfile ( argv[1] );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
main() takes parameters:
int main(int argc, char** argv) {
...
ifstream myfile (argv[1]);
...
}
You could also get clever, and loop for each file specified on the command line:
int main(int argc, char** argv) {
for (int file = 1; file < argc; file++) {
...
ifstream myfile (argv[file]);
...
}
}
Note that argv[0] is a string pointing to the name of your own program.
Main takes two arguments, which you can use to do this. See this:
Uni ref
MSDN reference (has VC specific commands