从由制表符分隔的文件中读取记录(Reading records from a file separated by tabs)

编程入门 行业动态 更新时间:2024-10-10 11:28:03
从由制表符分隔的文件中读取记录(Reading records from a file separated by tabs)

输入文件:

Joe Smith 10 Main St. 555-1212

我正在从具有上述格式的文件中读取记录,该文件包含由制表符分隔的3个字段,名称地址和电话号码。

while (fscanf(fp, "%s%s%s", rec[size].name, rec[size].address, rec[size].phone_number) != EOF) { size++; }

我必须为第一个单词添加空格并忽略选项卡并开始阅读下一个字段。

Input file:

Joe Smith 10 Main St. 555-1212

I'm reading a record from a file that has the above format which contains 3 fields, name address and phone number separated by tabs.

while (fscanf(fp, "%s%s%s", rec[size].name, rec[size].address, rec[size].phone_number) != EOF) { size++; }

I have to include the white space for the first word and ignore the tabs and start reading the next field.

最满意答案

char buffer[4096]; int n; while (fgets(buffer, sizeof(buffer), fp) != 0) { if ((n = sscanf(buffer, "%[^\t] %[^\t] %[^\t\n]", rec[size].name, rec[size].address, rec[size].phone_number)) != 3) { if (n != EOF) fprintf(stderr, "Error: faulty record without 3 fields at:\n%s", buffer); break; } size++; }

请注意,这使用fgets()来读取行。 它检查sscanf()读取三个字段。 你不应该得到n == EOF ,但测试以防万一。 错误消息在标准错误上报告,并包括导致问题的行( fgets()和sscanf()的主要优点之一是您为重试或错误报告捕获了行)。

char buffer[4096]; int n; while (fgets(buffer, sizeof(buffer), fp) != 0) { if ((n = sscanf(buffer, "%[^\t] %[^\t] %[^\t\n]", rec[size].name, rec[size].address, rec[size].phone_number)) != 3) { if (n != EOF) fprintf(stderr, "Error: faulty record without 3 fields at:\n%s", buffer); break; } size++; }

Note that this uses fgets() to read lines. It checks that sscanf() read three fields. You should not get n == EOF, but test just in case. The error message is reported on standard error, and includes the line that caused the trouble (one of the major advantages of fgets() plus sscanf() is that you have the line captured for retries or error reporting).

更多推荐

本文发布于:2023-07-27 02:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:制表符   文件   Reading   records   separated

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!