2016-11-15 30 views
0
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <time.h> 
#pragma warning(disable:4996) 

size_t file_size(FILE *fd){ 
    if (fd == NULL) { 
     printf("File not found"); 
     return -1; 
    } 
    fseek(fd, 0, SEEK_END);  
    return ftell(fd); 
} 

int main() { 
    FILE *in; 
    FILE *out; 

    char buffer[2] = { 0 }; 
    int n = 0; 
    in = fopen("test.txt", "rb"); 
    if (in == NULL) { 
     printf("cona\n"); return -1; 
    } 

    out = fopen("out.txt", "wb"); 
    if (out == NULL) { 
     printf("cona1\n"); return -1; 
    } 

    size_t size = file_size(in); 
    for(n = 0; n < size; n += 2){ 
     if (fread(&buffer, sizeof(char), 2, in) !=2) { 
      printf("cona2 \n"); 
     } //keeps given erros in here 
     fwrite(&buffer, sizeof(char), 2, out); 
     memset(buffer, 0, sizeof(buffer)); 
    } 
    printf(" \n in: %zu \n", size); 
    printf(" \n out: %zu \n", file_size(out)); 

    fclose(out); 
    fclose(in); 
    system("PAUSE"); 
    return(0); 
} 

我在這裏的主要問題是,如果fread函數在一個循環中起作用,並且如果我可以在文件ervytime中只詢問n個元素,而不是一次寫入所有文件,那麼我試試這個,讀取文件時出錯,它不會讀取任何內容。當你想要塊中的元素時,fread是否可以工作?

+1

如果在這個問題上是C++?在給定的代碼中我看不到任何東西。 –

+0

'return -1;'但函數的類型是'size_t',它是無符號的。這會在'main'中造成嚴重破壞,因爲無論如何您都不會檢查其有效性。 –

回答

2

還有就是你的函數後發現問題與

fseek(fd, 0, SEEK_END); 
return ftell(fd); 

文件的大小,因爲你不嘗試從中讀取之前倒帶至文件的開頭。

rewind(fd); 

fseek(fd, 0, SEEK_SET); 
+0

倒帶(fd)解決了問題,ty bruh –

+1

哇,我從來沒有成爲布魯赫。這是否值得銀牌或金牌? :) –

相關問題