How to write a file with C in Linux?

后端 未结 4 1533
忘了有多久
忘了有多久 2021-02-04 13:36

I want to rewrite the \"cp\" command of Linux. So this program will work like #./a.out originalfile copiedfile. I can open the file, create new file but can\'t writ

4条回答
  •  甜味超标
    2021-02-04 13:57

    First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.

    #include 
    
    int main(int argc, char **argv)
    {
        FILE* sourceFile;
        FILE* destFile;
        char buf[50];
        int numBytes;
    
        if(argc!=3)
        {
            printf("Usage: fcopy source destination\n");
            return 1;
        }
    
        sourceFile = fopen(argv[1], "rb");
        destFile = fopen(argv[2], "wb");
    
        if(sourceFile==NULL)
        {
            printf("Could not open source file\n");
            return 2;
        }
        if(destFile==NULL)
        {
            printf("Could not open destination file\n");
            return 3;
        }
    
        while(numBytes=fread(buf, 1, 50, sourceFile))
        {
            fwrite(buf, 1, numBytes, destFile);
        }
    
        fclose(sourceFile);
        fclose(destFile);
    
        return 0;
    }
    

    EDIT: The glibc reference has this to say:

    In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).

    If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.

提交回复
热议问题