Thread: Copy text from one file to other.

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    61

    Copy text from one file to other.

    The code is working nice for me.


    But feel free to give me advice.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define SIZE 100 
    
    
    int main(int argc, char** argv) {
    
    
        FILE *pFile;
        FILE *pFileOut;
    
    
        char string[SIZE];
    
    
        // Opening the file on reading mode and see if is valid.
        if ((pFile = fopen("code.txt", "rt")) == NULL) {
            printf("%d %s\n", errno, strerror(errno));
            return -1;
        }
    
    
        // Opening the file in writing mode and see if is valid.
        if ((pFileOut = fopen("new.txt", "wt")) == NULL) {
            printf("%d %s\n", errno, strerror(errno));
            fclose(pFile);
            return -1;
        }
    
    
        while (!feof(pFile)) { // feof returns 0 until it reach the end of the file. - !feof
            fgets(string, SIZE, pFile); // Going line by line, MAX SIZE, From where.
            if (fprintf(pFileOut, "%s", string) < 0) {
                printf("fprint got some error");
                fclose(pFileOut);
                fclose(pFile);
                return -1;
            }
        }
    
    
        fclose(pFileOut);
        fclose(pFile);
    
    
        return (EXIT_SUCCESS);
    }

  2. #2

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    61
    Quote Originally Posted by rags_to_riches View Post
    Code:
    // Donīt use !feof - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046476070&id=1043284351 - It reads "one too many times".
        while (fgets(string, sizeof (string), pFile) != NULL) { // Going line by line, MAX SIZE, From where.
            if (fprintf(pFileOut, "%s", string) < 0) {
                printf("fprint got some error");
                fclose(pFileOut);
                fclose(pFile);
                return -1;
            }
        }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copy defined parts from text-file
    By tomas.ra in forum C Programming
    Replies: 5
    Last Post: 02-19-2006, 01:44 PM
  2. How to copy a word or numbers from text to other location
    By trancedeejay in forum C Programming
    Replies: 12
    Last Post: 02-09-2006, 06:43 AM
  3. Copy and paste text
    By glue21 in forum C++ Programming
    Replies: 11
    Last Post: 10-07-2005, 08:24 AM
  4. Copy a text in BMP file
    By gardenair in forum Tech Board
    Replies: 6
    Last Post: 10-06-2003, 07:15 AM
  5. Replies: 1
    Last Post: 10-30-2002, 05:45 AM

Tags for this Thread