C:getcreturns-1
C: getc returns -1
我遇到的问题是这一行:
int tok = getc(fp);
getc returns -1。为什么?
提前致谢。
#include <stdio.h>
#include <memory.h>
#include "file_reader.h"
/**
* Opens a text file and reads the file. The text of the file is stored
* in memory in blocks of size blockSize. The linked list with the text is
* returned by the function. Each block should contain only complete words.
* If a word is split by the end of the block, the last letters should be
* moved into the next text block. Each text block must be NULL-terminated.
* If the reading of the file fails, the program should return a meaningful
* error message.
*/
LinkedList *read_text_file(const char* filename, int blockSize) {
int globalByteCounter = 0;
char *startPointer;
LinkedList* list = LinkedList_create();
int blockByteCounter;
FILE* fp = fopen(filename,"r");
int fileSize = getFileSize(fp);
while (globalByteCounter <= fileSize){
char* data="";
for (blockByteCounter = 0;blockByteCounter<blockSize;blockByteCounter++){
int tok = getc(fp);
printf("Tok: %d",tok);
strcat(data,(char*)tok);
}
LinkedList_append(list,data);
globalByteCounter+=blockByteCounter;
}
return list;
}
int getFileSize(FILE* file) {
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
return (int) size;
}
我删除了 fopen 并将方法更改为:
int getFileSize(FILE* file) {
FILE* endOfFile = file;
fseek(endOfFile, 0, SEEK_END);
long int size = ftell(file);
fseek(file, 0, SEEK_SET);
return (int) size;
}
我遇到的问题是这一行:
int tok = getc(fp);
getc returns -1。为什么? 提前致谢。
#include <stdio.h>
#include <memory.h>
#include "file_reader.h"
/**
* Opens a text file and reads the file. The text of the file is stored
* in memory in blocks of size blockSize. The linked list with the text is
* returned by the function. Each block should contain only complete words.
* If a word is split by the end of the block, the last letters should be
* moved into the next text block. Each text block must be NULL-terminated.
* If the reading of the file fails, the program should return a meaningful
* error message.
*/
LinkedList *read_text_file(const char* filename, int blockSize) {
int globalByteCounter = 0;
char *startPointer;
LinkedList* list = LinkedList_create();
int blockByteCounter;
FILE* fp = fopen(filename,"r");
int fileSize = getFileSize(fp);
while (globalByteCounter <= fileSize){
char* data="";
for (blockByteCounter = 0;blockByteCounter<blockSize;blockByteCounter++){
int tok = getc(fp);
printf("Tok: %d",tok);
strcat(data,(char*)tok);
}
LinkedList_append(list,data);
globalByteCounter+=blockByteCounter;
}
return list;
}
int getFileSize(FILE* file) {
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
return (int) size;
}
我删除了 fopen 并将方法更改为:
int getFileSize(FILE* file) {
FILE* endOfFile = file;
fseek(endOfFile, 0, SEEK_END);
long int size = ftell(file);
fseek(file, 0, SEEK_SET);
return (int) size;
}