2016-11-15 8 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

哇,我从来没有成为布鲁赫。这是否值得银牌或金牌? :) –

相关问题