#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个元素,而不是一次请求所有的文件,我尝试这样做,但它让我在读取文件时出错,它不会读取任何东西。
发布于 2016-11-16 04:44:59
在您的函数使用以下命令找到文件大小后出现问题
fseek(fd, 0, SEEK_END);
return ftell(fd);因为在尝试读取文件之前,您不会倒带到文件的开头。
rewind(fd);或
fseek(fd, 0, SEEK_SET);https://stackoverflow.com/questions/40619055
复制相似问题