fread does not insert a value

时间:2016-07-11 19:02:30

标签: c

i am getting a really weird problam when i am trying to start the program. the ## fread ##fuction does not insert to the vairabel (cu) a value. (line 7) does somebody knows why? or how i can solve it? the function ## marge ## gets two binary files that we know has numbers in increasing order and in the other file there are numbers in decreasing order. and it supposed to Combine them into one file in a increasing order.(i am not allowed to use any arrays or other data structure). thank you very much:) here is the code: (it in c language)

#include<stdio.h>
#define _NO_CRT_STDIO_INLINE
#pragma warning(disable:4996)
void marge(FILE* a, FILE* b) {
    FILE* res = fopen("C:\\Users\\shachar\\Desktop\\f.txt", "w+");
    int cu=0, cd=0, inx=1;
    fread(&cu,sizeof(int), 1, a);  // the problem is here!!
    fseek(b, 0, SEEK_END);         //cu stays 0
    fread(&cd, 4, 1, b);
    while (ftell(a)!=-1||ftell(b)){
        if (cu > cd) {
            fprintf(res, "%d ", cu);
            fread(&cu, 4, 1, a);
        }
        else {
            fprintf(res, "%d ", cu);
            fseek(b, SEEK_END, -inx);
            inx++;
            fread(&cd, 4, 1, b);
        }
    }
    while (ftell(a) != -1) {
        fprintf(res, "%d ", cu);
        fread(&cu, 4, 1, a);
    }
    while (ftell(b)){
        fprintf(res, "%d ", cu);
        fseek(b, SEEK_END, -inx);
        inx++;
        fread(&cd, 4, 1, b);
    }
    _fcloseall();
}

int main(void) {
    FILE* a = fopen("C:\\Users\\shachar\\Desktop\\x.txt", "r+" );
    FILE* b = fopen("C:\\Users\\shachar\\Desktop\\y.txt", "r+");
    marge(a, b);

}`

2 个答案:

答案 0 :(得分:4)

You aren't opening the files correctly. If you want to read from existing files, the last argument in your fopen should be 'r' not 'w'.

答案 1 :(得分:1)

It appears you only want to read from filestream a, so open it like so:

FILE* a = fopen("C:\\Users\\shachar\\Desktop\\x.txt", "r+" );

With w+ the file is truncated.

A similar problem may exist with b

相关问题