我想用 fscanf 在文本檔案中進行搜索。這是我正在搜索的數字,這些數字按值排序。因此,我想做一個二分查找,從中間開始等等。我的想法是先數數行數,除以二以求中間。但是如何告訴 fscanf 查看該行呢?
int seach_textfile(struct data *ean13, unsigned long long int *input)
{
FILE *fp_read = fopen("data.tex", "r");
unsigned long long int read, n_lines;
// count lines
n_lines = 0;
while (fscanf(fp_read,"\n") == 1)
{
n_lines ;
}
int n_line_low = 0;
int n_line_mid;
int n_line_high =n_lines;
while(n_line_high>n_line_low)
{
n_line_mid; = (n_line_low n_line_high)/2;
fscanf(fp_read,"%lld \n", read).... at n_line_mid // <----here!! (only to read first entr on line)
if(*input > read)
{
n_line_low = n_line_mid 1;
}
else
{
n_line_high = n_line_mid;
}
}
if(*input == read)
{
fscanf(fp_read,"%lld %s %s %s",*ean13->ean,*ean13->country,*ean13->manufacture,*ean13->product).... at n_line_mid // <----here!!
return 1;
}
else return 0;
}
uj5u.com熱心網友回復:
OP 的代碼無法找到行數,因為fscanf(fp_read,"\n")僅讀取前導空白并阻止第一個空白。
無論如何,行數并不是那么有用,因為它只是搜索以找到要查找的近似位置。檔案長度相同。
選擇
以二進制模式打開文本檔案。
快速確定其長度。(例如,重復
fread()s 的總和,或者fstat()如果可用)。left = 0; right = length-1mid = (left right)/2使用fseek(mid).fgetc()或fgets()到行尾:例如查找'\n'或EOF。讀號。如果匹配,我們就完成了。
如果太大,
right = mid - 1. 如果太小,left = ftell().如果
right >= left,則回圈回到步驟 4。失敗 - 未找到號碼。
一路檢查 I/O 函式回傳值。
如果代碼需要查找另一個數字,請省略第 2 步,因為檔案長度已知。
uj5u.com熱心網友回復:
我會先閱讀所有行并將它們存盤在鏈表中。然后你可以為所欲為。prev如果你倒退,你也可以添加指標。
typedef struct line
{
struct line *next;
char line[];
}line;
#define MAXLINE (8*1024)
line *readFile(FILE *fi, int removeLF)
{
char *workbuff = malloc(MAXLINE);
line *head = NULL, **current = &head;
if(fi && workbuff)
{
while(fgets(workbuff, MAXLINE, fi))
{
size_t len = strlen(workbuff);
*current = malloc(sizeof(**current) len 1);
if(current)
{
memcpy(current[0] -> line, workbuff, len 1);
if(removeLF && current[0] -> line[len - 1] == '\n') current[0] -> line[len - 1] = 0;
current = ¤t[0] -> next;
}
}
}
*current = NULL;
return head;
}
void print(line *lines)
{
size_t cline = 0;
do
{
printf("line no %zu = `%s`\n", cline, lines -> line);
lines = lines -> next;
}while(lines);
}
int main(void)
{
line *file = readFile(stdin, 1);
print(file);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378664.html
上一篇:在匯編語言中確定回傳值時遇到問題
下一篇:有沒有辦法從C字串中提取注釋?
