//* Reading text from one file and copying all lines to another file *

#ifdef _MSC_VER // for MS Visual Studio compilers - to allow "classic" insecure printf and scanf #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <string.h> #define max_line_size (256) int main() { // declare the file handles FILE *inFile; FILE *outFile; // declare variables to hold the file names char inName[80]; char outName[80]; // prompting user for filenames printf("Read text from: "); scanf(" %79[^\n]s\n", inName); printf("Write text to: "); scanf(" %79[^\n]s\n", outName); // actual opening of the file for reading from inFile = fopen(inName, "r"); if ( inFile==0 ) { printf("ERROR: Cannot open file %s for reading.\n", inName); return(1); } // actual opening of the file for writing to outFile = fopen(outName, "w"); if ( outFile==0 ) { printf("ERROR: Cannot open file %s for writing.\n", outName); fclose(inFile); return(1); } // reading-writing loop for (;;) { // reserving a variable for reading a line of text char line[max_line_size]; // assuming that each line is shorter than 255 characters // reading one line from the input file fgets(line, max_line_size, inFile); // <- this reads an entire line but it does include the trailing \n if ( feof(inFile) ) { // end of file - done reading break; } if ( ferror(inFile) ) { printf("Ann error was encountered while reading the file.\n"); } // printing the line to the output file fputs(line, outFile); } // closing the files fclose(inFile); fclose(outFile); return(0); }