Shows how to read from an #input file and write into an #output file through command line arguments using c and c plus plus languages. Shows how to do #file #handling and #compile and #run projects on visual studio 2017.
C code:
#include<stdio.h>
//int main()
int main(int argc, char *argv[])
{
printf("There are %d arguments.\n", argc);
for (int i = 0; i != argc; ++i)
{
printf("%s\n", argv[i]);
}
//char in_file[] = "test.txt";
char *in_file = argv[1];
FILE *input_file = fopen(in_file, "r");
char out_file[25] ;
//strcpy(out_file, "test.txt");
strcpy(out_file, argv[1]);
strcat(out_file, ".out");//output file name test.txt.out
FILE *output_file = fopen(out_file, "w");//w for write a for append
char line[25];
for (int line_no = 1; fgets(line, sizeof(line), input_file) != NULL; ++line_no)
{
//printf("LINE %d: %s", line_no, line);
//fprintf(output_file, "LINE %d: %s", line_no, line);
fputs(line, stdout);
fputs(line, output_file);
}
if (input_file)
{
fclose(input_file);
fclose(output_file);
}
getch();
return 0;
}
C++ code:
#include <iostream> //for cout
#include <fstream> // for ofstream/ifstream
#include <string> //for << and getline
//int main()
int main(int argc, char *argv[])
{
std::cout << "There are " << argc << " arguments." << std::endl;
for (int i = 0; i != argc; ++i)
{
std::cout << argv[i] << std::endl;
}
//std::string in_file = "test.txt";
std::string in_file = argv[1];
std::ifstream input_file(in_file.c_str());
//std::string out_file = "test.txt";
std::string out_file = argv[1];
out_file += ".out"; //output file name test.txt.out
std::ofstream output_file(out_file.c_str());
std::string line;
for (int line_no = 1; std::getline(input_file, line); ++line_no)
{
std::cout << "LINE " << line_no << ":" << line << std::endl;
output_file << "LINE " << line_no << ":" << line << std::endl;
}
if (input_file)
{
input_file.close();
output_file.close();
}
std::cin.get();
return 0;
}
#cplusplus #c #tutorial
C++ tutorial command line arguments
Passing Args To Main
How to pass command line argument in Visual Studio