[英]How to read files with strings and integers using fgets
我注意到fscanf
無法與確定的C編譯器(Intel,Cray)一起使用,因此我想使用fgets
讀取包含字符串和整數的簡單輸入文件
$cat input.txt
st 10 167 POP 456 244 NONE ENERGY
我可以做這樣的事情
int main()
{
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("input.txt", "r");
if (!ptr_file)
return 1;
for (int i = 0; i < 8; i++) {
fgets(buf, 1000, ptr_file);
printf("%s", buf);
}
fclose(ptr_file);
return 0;
}
讀取文件,然后創建一個switch case
以將buf
的值存儲為integer
或string
。 這顯然不是很有效,我想知道是否有人有更好的主意。
考慮使用sscanf,本質上是這樣的
// st 10 167 POP 456 244 NONE ENERGY
sscanf(buf, "%s %d %d %s %d %d %s %s", var1, &var2....);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.