c逐行读取文件我编写这个函数是为了从文件中读取一行:const char *readLine(FILE *file) {
if (file == NULL) {
printf("Error: file pointer is null.");
exit(1);
}
int maximumLineLength = 128;
char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);
if (lineBuffer == NULL) {
printf("Error allocating memory for line buffer.");
exit(1);
}
char ch = getc(file);
int count = 0;
while ((ch != '\n') && (ch != EOF)) {
if (count == maximumLineLength) {
maximumLineLength += 128;
lineBuffer = realloc(lineBuffer, maximumLineLength);
if (lineBuffer == NULL) {
printf("Error reallocating space for line buffer.");
exit(1);
}
}
lineBuffer[count] = ch;
count++;
ch = getc(file);
}
lineBuffer[count] = '\0';
char line[count + 1];
strncpy(line, lineBuffer, (count + 1));
free(lineBuffer);
const char *constLine = line;
return constLine;}函数正确地读取文件,并且使用printf,我看到Construcline字符串也被正确读取。但是,如果我使用这个函数,例如:while (!feof(myFile)) {
const char *line = readLine(myFile);
printf("%s\n", line);}printf输出胡言乱语。为什么?
3 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
getline()
#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>int main(void){ FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("/etc/motd", "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { printf("Retrieved line of length %zu:\n", read); printf("%s", line); } fclose(fp); if (line) free(line); exit(EXIT_SUCCESS);}
繁星淼淼
TA贡献1775条经验 获得超11个赞
FILE* fp;char buffer[255];fp = fopen("file.txt", "r");while(fgets(buffer, 255, (FILE*) fp)) { printf("%s\n", buffer);}fclose(fp);
- 3 回答
- 0 关注
- 705 浏览
添加回答
举报
0/150
提交
取消