0

I am trying to copy the contents from one file to another in c using the terminal on my mac.

I keep receiving this error when I try to compile the code, and I am unsure as to why.

This is my code:

#include <stdio.h>
#include <stdarg.h>

int main(int argc, char *argv[])
{
    FILE *f1Ptr, *f2Ptr;
    char x;

    if(argc != 3)
    {
        printf("Incorrect number of arguments\n");
    }

    f1Ptr = fopen(argv[1], "r");
    f2Ptr = fopen(argv[2], "w");

    if(f1Ptr == NULL || f2Ptr == NULL)
    {
        puts("File could not be opened");
    }

    while(!feof(f1Ptr))
    {
        x = fgetc(f1Ptr);
        fputc(x, f2Ptr);
    }

    printf("File has been copied\n");

    fclose(f1Ptr);
    fclose(f2Ptr);

return 0;
}

This is the error

ld: file too small (length=0) file 'file2.txt' for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Build command: "gcc q2.c file1.txt file2.txt ld: file too small (length=0) file 'file2.txt' for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Rebecca
  • 3
  • 2
  • 1
    Which error? Please copy **text** of the error and paste it to the body of your post. Don't link to screenshots. – n. m. could be an AI Mar 28 '17 at 19:53
  • 1
    "File could not be opened" is the canonical example of a bad error message. Which file? Why could it not be opened? There are lots of good examples of how to write a better error message. One such example is incidentally at an answer you must read for a different reason: http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell Mar 28 '17 at 19:53
  • Related: [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – John Bollinger Mar 28 '17 at 19:56
  • 1
    Please use the [edit] button to add the text of the error **to the body of your question**. Don't use comments for that. **Don't link to screenshots**. – n. m. could be an AI Mar 28 '17 at 19:56
  • 1
    It looks like you are trying to use `file2.txt` as an argument to the linker. This isn't likely to work. Please post your build command. – n. m. could be an AI Mar 28 '17 at 19:59

1 Answers1

2

You are trying to use the compiler to run the program. It doesn't work like that with C. You build the program, then you run it.

Moreover, C is not like interpreted languages such as Python or VM-based languages such as Java. When you successfully compile a C program you get a result that you can run directly. No interpreter or launcher is needed.

For example,

gcc -o q2 q2.c

./q2 file1.txt file2.txt 
./q2 file2.txt file3.txt 
./q2 file7.txt file42.txt 
John Bollinger
  • 160,171
  • 8
  • 81
  • 157