gpt4 book ai didi

c - 在 c 中将文本读入缓冲区。 (当文本文件中没有换行符时,省略最后一行数据)

转载 作者:行者123 更新时间:2023-12-04 10:10:39 28 4
gpt4 key购买 nike

我正在尝试通过为函数提供行号作为参数来将文本文件中的行读入缓冲区。然后此函数将文件的特定行中包含的文本复制到变量 retreiveString 中以供使用。我遇到的问题是,如果文本文件的末尾没有“空换行符”,程序不会将最后一个条目复制到缓冲区中。我做错了什么?

正确读取的文本文件示例

第 0 行

第 1 行


未将最后一行(即第 1 行)读入缓冲区的文本文件示例。

第 0 行

第 1 行

//test2
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 80

char read_in_buffer[BUFFER_SIZE];
char retreivedString[BUFFER_SIZE];
void getString(int lineNum);
int maxDataNum = 0;
bool endOfFileReached = false;

int main(void){
printf("-Main-\n");


getString(1);
printf("retrieved:%s\n",retreivedString);
printf("maxdata: %d\n",maxDataNum);
printf("strlen: %d",strlen(retreivedString));
/*
getString(2);
printf("retrieved: %s\n",retreivedString);
printf("maxdata: %d\n",maxDataNum);
getString(4);
printf("retrieved: %s\n",retreivedString);
printf("maxdata: %d\n",maxDataNum);
*/

return 0;
}

void getString(int lineNum){
FILE *fin=fopen("file1_Windows.txt","r");
int line_number = 0;
char *temp;


if(fin==NULL){
printf("cannot open file1_Windows.txt\n");
}
while (1){

memset(read_in_buffer,0,sizeof(read_in_buffer));
fgets(read_in_buffer,sizeof(read_in_buffer),fin); //change to segment size?

if (!feof(fin)) {
if (lineNum == line_number){
memset(retreivedString,0,sizeof(retreivedString));
strcpy(retreivedString,read_in_buffer);
}
//printf("current line %d: ",line_number);
//printf("%s",read_in_buffer);
line_number++;

}else {
fclose(fin);
printf("End-of-File reached. \n");
maxDataNum = line_number;
printf("maxdata: %d\n",maxDataNum);

if (lineNum == maxDataNum){
endOfFileReached = true;
}else if (lineNum > maxDataNum){
printf("file read error, you're reading further that data on file\n");
}

break;
}

}

}

最佳答案

这样做。如果 fopen 调用失败,它将返回并将 fgets 调用置于 while 循环中:

void getString(int lineNum){
FILE *fin=fopen("file1_Windows.txt","r");
int line_number = 0;
char *temp;


if(fin==NULL){
printf("cannot open file1_Windows.txt\n");
return;
}
memset(read_in_buffer,0,sizeof(read_in_buffer));
while (fgets(read_in_buffer,sizeof(read_in_buffer),fin) != NULL){
if (lineNum == line_number){
memset(retreivedString,0,sizeof(retreivedString));
strcpy(retreivedString,read_in_buffer);
}
//printf("current line %d: ",line_number);
//printf("%s",read_in_buffer);
line_number++;
memset(read_in_buffer,0,sizeof(read_in_buffer));
}
fclose(fin);
printf("End-of-File reached. \n");
maxDataNum = line_number;
printf("maxdata: %d\n",maxDataNum);
if (lineNum == maxDataNum){
endOfFileReached = true;
}else if (lineNum > maxDataNum){
printf("file read error, you're reading further that data on file\n");
}
}

关于c - 在 c 中将文本读入缓冲区。 (当文本文件中没有换行符时,省略最后一行数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6138311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com