Read Write File (handling) in c and c++ Character by Character with Char 20

Опубликовано: 05 Июль 2026
на канале: Arif Mahmood
111
1

Shows how to #read/#write a file with #characters. How to change #char to #string. How to read #input from a #file letter by letter in c plus plus and c language #program.

c code:

#include<stdio.h>
int main()
{
FILE *input_file;
char in_file[] = "test.txt";//string
input_file = fopen(in_file, "r");

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

int line;
//char line;

//for (; (line = fgetc(input_file)) != EOF;)
//{
// //printf("%c\n", line);
// //fprintf(output_file, " %c\n", line);
// //printf("%s\n", (char[2]) { line, 0 });//convert char to string
// //fprintf(output_file, " %s\n", (char[2]) { line, 0 });
// printf("%s\n", (char[sizeof(line)]) { line, 0 });//convert int to string
// fprintf(output_file, " %s\n", (char[sizeof(line)]) { line, 0 });
//}

for (; (line = getc(input_file)) != EOF;)
{
printf("%c\n", line);
fprintf(output_file, " %c\n", 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::string in_file = "test.txt";
std::ifstream input_file(in_file);

in_file += ".out";
std::ofstream output_file(in_file);

char line;

//while (input_file >> std::skipws >> line)
////for (;input_file >> std::noskipws >> line;)
//{
// std::cout << line << std::endl;
// output_file << line << std::endl;
// //std::cout << std::string(1, line)<<std::endl;
// //output_file << std::string(1, line)<<std::endl;
//}

for (;input_file.get(line);)
{
std::cout << line << std::endl;
output_file << line << std::endl;
}

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

#c++ #c #tutorial