[英]How to read data from a file in C?
I have a file containing the information 我有一个包含信息的文件
0001:Jack:Jeremy:6:38.0
0002:Mat:Steve:1:44.5
0003:Jessy:Rans:10:50.0
0004:Van Red:Jimmy:3:25.75
0005:Peter:John:8:42.25
0006:Mat:Jeff:3:62.0
I want to get data from this file so each part of this string will have each value. 我想从该文件中获取数据,以便此字符串的每个部分都具有每个值。 For example,
double num
will be 3; 例如,
double num
将为3; char firstn[20]
will be 'Jack', char lastn[20]
will be 'Jeremy', int t
will be 6, and double hour
will be 38.0, and so on. char firstn[20]
将为'Jack', char lastn[20]
将为'Jeremy', int t
将为6, double hour
将为38.0,依此类推。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *read, *write;
int i, group;
double hours, num;
char lastn[20],
firstn[20];
read = fopen("people.txt", "r");
if (read == NULL) {
printf("Error, Can not open the file\n");
exit(0);
}
write = fopen("people.dat", "w");
for (i=0; i<6; i++) {
fscanf(read, "%lf:%s:%s:%d:%lf", &num, lastn, firstn, &group, &hours);
fprintf(write, "Number: %lf Fname: %s Lastn: %s Group: %d Hours: %.1lf\n", num, lastn, firstn, group, hours);
}
fclose(read);
fclose(write);
return 0;
}
When I am trying to do so, my string lastn
takes all the information until the end of line. 当我尝试这样做时,我的字符串
lastn
将获取所有信息,直到行尾为止。
How can I specify so string firstn
will take only characters until :
and then string lastn
will take only Jeremy, and group will take only 6, and so on? 如何指定字符串
firstn
仅包含字符直到:
,然后字符串lastn
仅包含Jeremy,组仅包含6,依此类推?
You can modify your fscanf()
format string. 您可以修改
fscanf()
格式字符串。
if (fscanf(read, "%lf:%19[^:]:%19[^:]:%d:%lf", &num, lastn, firstn, &group, &hours) != 5)
...the read failed...
The notation %19[^:]
means 'read up to 19 non-colon characters' into the string, followed by a null. 符号
%19[^:]
表示“最多读取19个非冒号字符”到字符串中,后跟一个null。 Note that the variables lastn
and firstn
are char[20]
. 请注意,变量
lastn
和firstn
是char[20]
。 Note that the conversion is checked; 请注意,已检查转换。 if you get an answer other than 5, something went wrong.
如果您得到的答案不是5,则出问题了。 You might consider scanning the rest of the line up to a newline after the
fscanf()
call: 您可以考虑在
fscanf()
调用之后将行的其余部分扫描到换行符:
int c;
while ((c = getc(read)) != EOF && c != '\n')
;
You should also check that you succeeded in opening the output file. 您还应该检查是否成功打开了输出文件。
Use fgets()
to read line and then tokenize it using strtok()
使用
fgets()
读取行,然后使用strtok()
将其标记化
char line[100];
char *p;
fgets(line);
p = strtok(line, ":");
Now you can store tokens into variables as you like. 现在,您可以根据需要将令牌存储到变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.