我正在寻找一种方法来使用C中的唯一void函数读取文件和stdin流.我正在尝试使用此功能:
#define ENTER 10 //'\n' ASCII code
........
void read(FILE *stream, char *string) {
char c;
int counter = 0;
do {
c = fgetc(stream);
string = realloc(string, (counter+1) * sizeof(char));
string[counter++] = c;
} while(c != ENTER && !feof(stream));
string[counter-1] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
但它只适用于stdin流.当我使用文本文件时,文件内容在函数外部不可见.我正在调用这个函数:
read(stdin, inputString);
read(inputFile, fileContent);
Run Code Online (Sandbox Code Playgroud)
并且仅在第一种情况下正常工作.
PS:最初,inputString的fileContent已被声明为
char *inputString = malloc(sizeof(char));
char *fileContent = malloc(sizeof(char));
Run Code Online (Sandbox Code Playgroud)
我知道fgetc返回int,char重新分配的char很昂贵(但我只需要使用必要的内存)而EOF或'\n'存储在字符串中(但后面用0-terminator替换).
我在使用fileContent变量的代码中遇到了麻烦.我希望fileReader重新分配所做的更改在我的主要工作正常,但它不起作用..
void fileReader(char *fileName, char *fileContent){
FILE *inputFile = fopen(fileName, "r");
int fileLength = 0;
int endFlag = fgetc(inputFile);
while(endFlag != EOF){
fileContent = (char *) realloc (fileContent, (fileLength + 1) * sizeof(char));
fileContent[fileLength] = endFlag;
endFlag = fgetc(inputFile);
fileLength++;
}
}
int main(int argc, char const *argv[]){
char *fileName = (char *) malloc (sizeof(char));
char *taskStack = (char *) malloc (sizeof(char));
char *fileContent = NULL;
inputReader(fileName, taskStack);
fileReader(fileName, fileContent);
return 0;
}
Run Code Online (Sandbox Code Playgroud)