File Handling (read / write) in c and c++ on Visual Studio 2017 1

Опубликовано: 27 Апрель 2026
на канале: Arif Mahmood
11,757
69

Shows how to #read from an input #file and #write into an output file 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>
//_CRT_SECURE_NO_WARNINGS

int main()
{
//FILE *input_file;
//input_file = fopen("test.txt", "r");
//FILE *input_file = fopen("test.txt", "r");
char in_file[] = "test.txt";
FILE *input_file = fopen(in_file, "r");

//FILE *output_file = fopen("test.txt.out", "w");//w for write a for append
char out_file[] = "test.txt"".out";
FILE *output_file = fopen(out_file, "w");//w for write a for append

char line[50];
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);
}

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()
{
//std::ifstream input_file;
//input_file.open("test.txt");
//std::ifstream input_file("test.txt");
std::string in_file = "test.txt";
std::ifstream input_file(in_file.c_str());

//std::ofstream output_file("test.txt.out");
//std::string out_file = "test.txt"".out";
std::string out_file = "test.txt";
out_file += ".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

Writing and reading to a File Using C Programming
C++ Writing & Reading Files
C++ how to read and write to a file