how to get the source file's (the file which I want to copy) and the copied file's information in C

烈酒焚心 提交于 2019-12-02 07:30:53

I am unsure where your difficulty lies, apart from errors mentioned in comment. I've simplified your code, removing the bitfield masks as I don't have their definitions.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int ch;                                 // <--- int not char
    struct stat sb;
    FILE *source, *target;

    if (argc < 3) {
        printf("Enter two args: source and destination file names\n");
        exit(EXIT_FAILURE);
    }
    source = fopen(argv[1], "r");
    if( source == NULL ) {
        printf("Press any key to exit...\n");
        exit(EXIT_FAILURE);
    }

    target = fopen(argv[2], "w");
    if( target == NULL ) {
        fclose(source);
        printf("Press any key to exit...\n");
        exit(EXIT_FAILURE);
    }

    while( ( ch = fgetc(source) ) != EOF )
        fputc(ch, target);
    fclose(source);
    fclose(target);
    printf("File copied successfully.\n");

    if (stat(argv[1], &sb) == -1) {
        perror("stat");
        exit(EXIT_SUCCESS);
    }
    printf("File %s type: 0x%04X Mode: 0x%04X\n", argv[1], (unsigned)sb.st_ino, (unsigned)sb.st_mode);

    if (stat(argv[2], &sb) == -1) {
        perror("stat");
        exit(EXIT_SUCCESS);
    }
    printf("File %s type: 0x%04X Mode: 0x%04X\n", argv[2], (unsigned)sb.st_ino, (unsigned)sb.st_mode);

    return 0;
}

Program output:

>test test.c test2.c
File copied successfully.
File test.c type: 0x0000 Mode: 0x81B6
File test2.c type: 0x0000 Mode: 0x81B6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!