Read Multiple Input Files in c++ and c# with Command Line Arguments 69

Опубликовано: 04 Май 2026
на канале: Arif Mahmood
3,838
21

Shows how to read from multiple input files with and without using command line arguments in c plus plus and c sharp programs.

c++ code:


#include <iostream> //for cout
#include <fstream> // for ofstream/ifstream
#include <string> //for << and getline

//int main()
int main(int argc, char *argv[])
{
if (argc < 3)
{
std::cerr << "provide 2 input file names for command line args in properties."
<< std::endl;
std::cin.get();
return -1;
}

std::cout << "There are " << argc << " arguments." << std::endl;
for (int i = 0; i != argc; ++i)
{
std::cout << argv[i] << std::endl;
}

//std::ifstream input_file1("test1.txt");
//std::ifstream input_file2("test2.txt");
std::ifstream input_file1(argv[1]);
std::ifstream input_file2(argv[2]);

std::ofstream output_file("test.txt.out");

std::string line;
int line_no = 1;

for (; std::getline(input_file1, line); ++line_no)
{

std::cout << line_no << ":" << line << std::endl;
output_file << line_no << ":" << line << std::endl;
}

for (; std::getline(input_file2, line); ++line_no)
{

std::cout << line_no << ":" << line << std::endl;
output_file << line_no << ":" << line << std::endl;
}

//if (input_file1)
if (input_file1 && input_file2)
{
input_file1.close();
input_file2.close();

output_file.close();
}
std::cin.get();
return 0;
}



c# code:


using System;
using System.IO;//to use StreamReader
namespace lec1csharp
{
class Program
{
//static void Main()
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.Error.WriteLine(
"provide 2 input file names for command line args in properties.");
Console.ReadLine();
return;
}

Console.WriteLine("There are {0} arguments.", args.Length);
for (int i = 0; i != args.Length; ++i)
{
Console.WriteLine(args[i]);
}

//StreamReader input_file1 = new StreamReader("test1.txt");
//StreamReader input_file2 = new StreamReader("test2.txt");
StreamReader input_file1 = new StreamReader(args[0]);
StreamReader input_file2 = new StreamReader(args[1]);

StreamWriter output_file = new StreamWriter("test.txt.out");

string line = "";
int line_no = 1;

for (; (line = input_file1.ReadLine()) != null; ++line_no)
{
Console.WriteLine(" {0} :{1}", line_no, line);
output_file.WriteLine(" {0} :{1}", line_no, line);
}

for (; (line = input_file2.ReadLine()) != null; ++line_no)
{
Console.WriteLine(" {0} :{1}", line_no, line);
output_file.WriteLine(" {0} :{1}", line_no, line);
}

//if (input_file1 != null)
if (input_file1 != null && input_file2 != null)
{
input_file1.Close();
input_file2.Close();

output_file.Close();
}

Console.ReadLine();
}
}
}


#cplusplus #csharp #tutorial

Tutorial Reading from Files in C#
Reading From and Writing To Text Files in C#
How to Read and Write to Text File C# Tutorial