动态添加到大小未知的char数组

时间:2018-10-15 21:56:37

标签: c arrays dynamic malloc realloc

我目前正在做一个作业,我必须一次从每个文件中提取一个字符,然后将它们连接起来并打印出来。我找到了一种提取字符并将其保存在变量a-d中的方法。如何将这些char添加到char数组中以打印到末尾?我最初将其分配为char的大小,并在每个if语句中重新分配。我在网上找到的所有指南都建议我使用strcat,但是无法传递a-d变量来追加。我该如何解决?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>


pthread_mutex_t thread1;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
char *output;

void* processing(void* file) {
    FILE *test = fopen("drive1.data", "r");
    FILE *drive1 = fopen("drive1.data", "r");
    FILE *drive2 = fopen("drive2.data", "r");
    FILE *drive3 = fopen("drive3.data", "r");
    FILE *drive4 = fopen("drive4.data", "r");
    FILE *drive5 = fopen("drive5.data", "r");
    int c, a, b, e, d;
    int control = 0;

    //Initializingn the char array with initial size 1
    output = (char *)malloc(sizeof(char));

    while(!feof(drive1)) {
        if(control == 0) {
            pthread_mutex_lock(&thread1);
            //printf("Mutex lock\n");
            c = getc(drive1);
            output = realloc(output, sizeof(output) + sizeof(char));
            printf("%c\n", (char)c);
            strcat(output, (char)c);
            control++;
            pthread_mutex_unlock(&thread1);
            //printf("Mutex unlock\n");
        } else if(control == 1) {
            pthread_mutex_lock(&thread1);
            //printf("Mutex lock\n");
            a = getc(drive2);
            printf("%c\n", (char)a);
            control++;
            pthread_mutex_unlock(&thread1);
            //printf("Mutex unlock\n");
        } else if(control == 2) {
            pthread_mutex_lock(&thread1);
            //printf("Mutex lock\n");
            b = getc(drive3);
            printf("%c\n", (char)b);
            control++;
            pthread_mutex_unlock(&thread1);
            //printf("Mutex unlock\n");
        } else if(control == 3) {
            pthread_mutex_lock(&thread1);
            //printf("Mutex lock\n");
            d = getc(drive4);
            printf("%c\n", (char)d);
            control++;
            pthread_mutex_unlock(&thread1);
            //printf("Mutex unlock\n");
        } else if(control == 4) {
            pthread_mutex_lock(&thread1);
            //printf("Mutex lock\n");
            e = getc(drive5);
            printf("%c\n", (char)e);
            control = 0;
            pthread_mutex_unlock(&thread1);
            //printf("Mutex unlock\n");
        }
    }
}

int main() {
    pthread_t th1;
    pthread_create(&th1, NULL, processing, NULL);
    pthread_join(th1, NULL);

}

0 个答案:

没有答案