动态内存分配给文件操作Strcat不起作用

发布于 2025-02-06 07:42:59 字数 817 浏览 1 评论 0原文

Strcat不起作用。我正在尝试读取具有动态内存功能的两个文件中的文本。我不明白错误在哪里。

这是我的代码:

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

void fileTest (char* filename, char c[]){

    char* s = (char*) malloc(sizeof(char) * 1000);

    FILE *fp =fopen(filename, "r");
    if (fp == NULL){
        exit(-1);
    }
    while( !feof(fp)){
        fgets(s,100,fp);
        strcat(c,s);
    }

    free(s);
    fclose(fp);


}

int main() {

    char firstS []="";
    char secondS []="";
    fileTest("file.txt", firstS);
    fileTest("file2.txt", secondS);
    printf("Fist file: %s \n", firstS);
    printf("Second file: %s", secondS);

    return 0;
}

在file.txt中写下“ hello”,in file2.txt上写下“世界”,我将获得此输出:错误图像如何修复此代码?

Strcat is not working. I am trying to read text from 2 files with a dynamic memory function. I could not understand where is the error.

This is my code:

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

void fileTest (char* filename, char c[]){

    char* s = (char*) malloc(sizeof(char) * 1000);

    FILE *fp =fopen(filename, "r");
    if (fp == NULL){
        exit(-1);
    }
    while( !feof(fp)){
        fgets(s,100,fp);
        strcat(c,s);
    }

    free(s);
    fclose(fp);


}

int main() {

    char firstS []="";
    char secondS []="";
    fileTest("file.txt", firstS);
    fileTest("file2.txt", secondS);
    printf("Fist file: %s \n", firstS);
    printf("Second file: %s", secondS);

    return 0;
}

In file.txt writes "Hello", in file2.txt writes "World" and I am getting this output : Error Image How can I fix this code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文