我在用 C 语言打开文件时遇到问题
I have problems with opening file in C
我假设我遇到了编译问题,但我想确定这不是我的错。
我将我的代码与几天前编写的程序中的其他代码进行了比较,我确实找不到任何区别。
FILE *f;
f = fopen("gps.txt","r");
if (f == NULL){
printf("Couldn't open the file.");
return 0;
}
int i= 0;
int n;
while(fscanf(f,"%c %d %d %d %c %d %d %d %d %d %d",&gps[i].sirina,&gps[i].stepen,&gps[i].min,&gps[i].sek,&gps[i].duzina,&gps[i].s1,&gps[i].m1,&gps[i].sek1,&gps[i].visina,&gps[i].brzina,&gps[i].sateliti)==11)
i++;
n = i;
printf("%d",gps[1].sek);
文件信息:(25 55 22 N 123 213 123 S 25 23 2
123 123 123 N 234 25 53 S 123 5 1
12 41 3 N 12 5 13 S 1 2 4)
此代码的结果始终为 0(这只是为了检查我是否可以继续执行我的程序)。文件中写有信息,我仔细检查我每次都保存了它,但我的程序仍然输出 0。在我几天前写的相同代码上,输出没问题,包括文件相同的事实。
我很高兴知道是否存在编译问题或我的代码是否有错误。谢谢!
根据您的输入,fscanf 中的字符串是错误的。
您使用以下字符串:
%c %d %d %d %c %d %d %d %d %d %d"
这是输入行的示例:
25 55 22 N 123 213 123 S 25 23 2
您需要以下字符串:
%d %d %d %[^A-Z] %c %d %d %d %[^A-Z] %c %d %d %d
根据给定的示例,您使用 %d 读取了 25、55、22。
然后你使用 %[^A-Z]
跳过 spaces 等,然后你使用 %c
阅读 N 或 S。
space也是一个字符,需要注意一下。
我假设我遇到了编译问题,但我想确定这不是我的错。
我将我的代码与几天前编写的程序中的其他代码进行了比较,我确实找不到任何区别。
FILE *f;
f = fopen("gps.txt","r");
if (f == NULL){
printf("Couldn't open the file.");
return 0;
}
int i= 0;
int n;
while(fscanf(f,"%c %d %d %d %c %d %d %d %d %d %d",&gps[i].sirina,&gps[i].stepen,&gps[i].min,&gps[i].sek,&gps[i].duzina,&gps[i].s1,&gps[i].m1,&gps[i].sek1,&gps[i].visina,&gps[i].brzina,&gps[i].sateliti)==11)
i++;
n = i;
printf("%d",gps[1].sek);
文件信息:(25 55 22 N 123 213 123 S 25 23 2
123 123 123 N 234 25 53 S 123 5 1
12 41 3 N 12 5 13 S 1 2 4)
此代码的结果始终为 0(这只是为了检查我是否可以继续执行我的程序)。文件中写有信息,我仔细检查我每次都保存了它,但我的程序仍然输出 0。在我几天前写的相同代码上,输出没问题,包括文件相同的事实。
我很高兴知道是否存在编译问题或我的代码是否有错误。谢谢!
根据您的输入,fscanf 中的字符串是错误的。 您使用以下字符串:
%c %d %d %d %c %d %d %d %d %d %d"
这是输入行的示例: 25 55 22 N 123 213 123 S 25 23 2
您需要以下字符串:
%d %d %d %[^A-Z] %c %d %d %d %[^A-Z] %c %d %d %d
根据给定的示例,您使用 %d 读取了 25、55、22。
然后你使用 %[^A-Z]
跳过 spaces 等,然后你使用 %c
阅读 N 或 S。
space也是一个字符,需要注意一下。