我想从输入文件的最后一行的第6列打印一个整数" out"。
以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len = 0;
int n2 = 0;
int n3 = 0;
char line[1000];
char *pch;
char c[6] = "ATOM ";
FILE *fp = fopen("1PGB.pdb", "r");
FILE *op = fopen("out", "w");
if (fp == NULL || op == NULL) {
fprintf(stderr, "Error opening file.\n");
exit(1);
} else {
while (fgets(line, sizeof(line), fp) != 0)
if ((pch = strstr (line, c)) != NULL)
fprintf(op, "%s\n", line);
}
fclose(fp);
fclose(op);
FILE *ip = fopen("out", "r");
fseek(ip, 1, SEEK_END);
if (fgets(line, len, ip) != NULL)
puts(line);
else
printf("Error\n");
fclose(ip);
}
预计会返回文件的最后一行&#34; out&#34;。
它提供输出:错误
文件的最后几行是:
ATOM 427 N GLU A 56 7.248 9.043 7.175 1.00 16.36 N
ATOM 428 CA GLU A 56 6.283 8.177 6.480 1.00 19.22 C
ATOM 429 C GLU A 56 6.780 7.744 5.081 1.00 22.26 C
ATOM 430 O GLU A 56 7.521 8.520 4.401 1.00 23.58 O
ATOM 431 CB GLU A 56 4.960 8.864 6.307 1.00 19.26 C
ATOM 432 CG GLU A 56 4.093 8.873 7.512 1.00 19.10 C
ATOM 433 CD GLU A 56 2.702 9.417 7.201 1.00 18.54 C
ATOM 434 OE1 GLU A 56 2.544 10.440 6.499 1.00 18.16 O
ATOM 435 OE2 GLU A 56 1.737 8.791 7.641 1.00 20.42 O
ATOM 436 OXT GLU A 56 6.410 6.617 4.667 1.00 24.74 O
我想打印整数&#34; 56&#34;在最后一行的第6列。
答案 0 :(得分:2)
省略输出文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len = 0;
int n2 = 0;
int n3 = 0;
int result=0;
char line[1000];
char lastline[1000]="";
char *pch;
char c[6] = "ATOM ";
FILE *fp = fopen("1PGB.pdb", "r");
//FILE *op = fopen("out", "w");
if (!fp) {
fprintf(stderr, "Error opening file.\n");
exit(1);
} else {
while (fgets(line, sizeof(line), fp) != 0)
if ((pch = strstr (line, c)) != NULL){
strcpy(lastline,line); //save content of the last output
printf("%s", line);
}
}
fclose(fp);
if(*lastline){
strtok(lastline," "); //skip first field
for(int i=0;i<4;i++) // skip next 4 fields (5 in total)
strtok(NULL," ");
sscanf(strtok(NULL," "),"%d",&result);//get and convert the 6th field
printf("LastLine: %d\n",result); //print it
}
return 0;
}