【问题标题】:Trying to copy contens of a file multiple times into another file in c尝试将文件的内容多次复制到c中的另一个文件中
【发布时间】:2021-11-29 02:43:30
【问题描述】:

我正在尝试用 c 编写一个程序,该程序将一个文件的内容多次复制到另一个文件中,但出现了问题。出现一些奇怪的字符,而且只复制一次。

c 代码

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

char* laod_with_correct_size(char* file_location, int size) {

    char* buffer=NULL;
    FILE* file;
    size=0;
    int len;

    file=fopen(file_location,"rb");
    if(file==NULL) {
        fclose(file);
        return NULL;
    }

    fseek(file,0,SEEK_END);

    len=ftell(file);

    if(len<1) {
        fclose(file);
        return NULL;
    }
    
    rewind(file);

    buffer=(char*) malloc(len);
    if(buffer==NULL) {
        fclose(file);
        return NULL;
    }

    if(fread(buffer,1,len,file)!=(size_t)len) {
        free(buffer);
        fclose(file);
        return NULL;
    }
    fclose(file);
    size=len;
    printf("Size in fucntion is %d\n",len);    

    return buffer;
}

int get_size(char* filepath) {
    FILE* f;
    int len;
    f=fopen(filepath,"rb");
    fseek(f,0,SEEK_END);
    len=ftell(f);
    fclose(f);
    printf("TOTAL SIZE THAT SHOULD BE IN THE FUCNTION IS %d",len);
}

 int write_correctly(char* file,char* buffer,int len) {
     // printf("len size is %d\n",len);
     int file_descriptor = open(file,O_APPEND || O_CREAT);
     int len_to_use=get_size(file);
     int size=write(file_descriptor,buffer,len_to_use);
     printf("Second size in fucntion is %d\n",size);    
     close(file_descriptor);

     printf("SIZE OF SIZE+1 IS %d and SIZE OF LEN IS %d\n",size+1,len);
     if(size!=len) {
         return-1;

     } else {
         return size;

     }
 }



int main(int argc,char** argv) { 
    int size=0;
    size=get_size(argv[1]);
    char* buffer=laod_with_correct_size(argv[1],size);
    printf("Size of %s is %d\n",argv[1],size);
    // if(write_correctly(argv[2],buffer,size)<0) {
    //     printf("Couldn't write\n");
    // }
    write_correctly(argv[2],buffer,size);
    write_correctly(argv[2],buffer,size);
    write_correctly(argv[2],buffer,size);
    write_correctly(argv[2],buffer,size);
    

    return 0;
}

第一个文件(从中复制)

salut
buna
alo

第二个文件(复制到)

salut
buna
alo
\00\00\00\00\00\00\00\00\00Q\F7\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00

我的指针生锈了,但我希望我没有犯任何重大错误。

【问题讨论】:

  • 次要:当fopen() 失败时,您不需要调用fclose()。使用无效的流指针调用 fclose() 是未定义的行为。

标签: c file pointers


【解决方案1】:

函数get_size 被声明为返回int 类型的值,但从不返回值。

通过在函数mainwrite_correctly 中使用这些不存在的返回值,您的程序正在调用未定义的行为。

此外,在函数write_correctly 中,您尝试写入的数据量等于现有输出文件的大小是没有意义的。相反,您应该始终写入缓冲区的大小,这应该是输入文件的大小。

如果您在debugger 中逐行运行程序,同时监控所有变量的值,您可能会发现更容易理解程序中发生了什么。

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2022-11-24
    • 1970-01-01
    • 2018-05-10
    • 2021-11-02
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多