如果第一個字符是#,則需要跳過整行(注釋)
建議其他帖子中的一些解決方案,fgets
但在我的情況下fscanf是首選選項,因為我需要稍后逐個決議每個單詞。怎么能做到這一點fscanf呢?謝謝你。
要讀取的檔案
#This line is a comment <== skip this entire line
BEGIN {
THIS IS A WORD
}
代碼
void read_file(FILE *file_pointer, Program *p)
{
char buffer[FILESIZE];
int count = 0;
while (fscanf(file_pointer, "%s", buffer) != EOF)
{
if (buffer[0] == '#')
{
continue; <============ need to skip until the end of the line
}
else
{
strcpy(p->wds[count ], buffer);
}
}
}
uj5u.com熱心網友回復:
怎么能做到這一點
fscanf呢?
fscanf(stdin, "%*[^\n]"); 將讀取除換行符以外的所有字符,直到發生錯誤或檔案結束。
* 表示禁止分配正在讀取的資料。
默認情況下,[啟動要接受的字串列。但是,^否定了這一點;[^\n]表示接受除換行符以外的所有字符。
uj5u.com熱心網友回復:
其他帖子中的一些解決方案建議使用 fgets,但在我的情況下 fscanf 是首選選項,因為我需要稍后逐個決議每個單詞。僅使用 fscanf 怎么能做到這一點?
我建議您使用fgets閱讀整行,然后您可以使用sscanf而不是fscanf逐字閱讀該行。
#include <stdio.h>
void read_file( FILE *file_pointer )
{
char line[100];
while ( fgets( line, sizeof line, file_pointer) != NULL )
{
char *p = line;
char word[50];
int chars_read;
//skip line if it starts with "#"
if ( line[0] == '#' )
{
continue;
}
//read all words on the line one by one
while ( sscanf( p, "Is%n", word, &chars_read ) == 1 )
{
//do something with the word
printf( "Found word: %s\n", word );
//make p point past the end of the word
p = chars_read;
}
}
}
int main( void )
{
//this function can also be called with an opened file,
//however for simplicity, I will simply pass "stdin"
read_file( stdin );
}
隨著輸入
This is a test.
#This line should be ignored.
This is another test.
該程式具有以下輸出:
Found word: This
Found word: is
Found word: a
Found word: test.
Found word: This
Found word: is
Found word: another
Found word: test.
如您所見,以 開頭的行#已成功跳過。
uj5u.com熱心網友回復:
fgets()在您閱讀第一個單詞后使用以閱讀該行的其余部分。
while (fscanf(file_pointer, "%s", buffer) != EOF)
{
if (buffer[0] == '#')
{
fgets(file_pointer, buffer, sizeof buffer);
}
else
{
strcpy(p->wds[count ], buffer);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418553.html
標籤:
