C编程:将特定列的值从一个文件写入另一个文件时出错
我想将第6列的值从一个文件存储到另一个文件 以下是我的代码:C编程:将特定列的值从一个文件写入另一个文件时出错,c,file,segmentation-fault,C,File,Segmentation Fault,我想将第6列的值从一个文件存储到另一个文件 以下是我的代码: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { unsigned int number_of_lines = 0; int n6 = 0; char line[1000]; char line2[100]; char line3[1000]; char *p
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
unsigned int number_of_lines = 0;
int n6 = 0;
char line[1000];
char line2[100];
char line3[1000];
char *pch;
int l;
char *pch2;
char c[6] = " N ";
FILE *fp = fopen("1PGB.pdb", "r"); // This opens the 1PGB.pdb in read-only mode
FILE *op = fopen("out", "w"); // This opens the out file in write mode
char lastline[100]=" ";
if(fp == NULL || op == NULL)
{
fprintf(stderr, "Error opening file.");
exit(1);
}
else
{ // This loop is for printing only the lines containing " N " into out file
while (fgets(line, sizeof(line), fp) != 0)
{
if((pch = strstr (line, c))!= 0)
fprintf(op, "%s", line);
}
}
fclose(fp); // Closes 1PGB.pdb
fclose(op); // Closes out file
FILE *ip = fopen("out", "r"); // Opens out file in read mode
FILE *op2 = fopen("out2", "w"); // Opens out2 file in write mode
if(!ip)
{
fprintf(stderr, "Error\n");
exit(1);
}
while (fgets(line3, sizeof(line3), ip) != 0)
{
sscanf(line3, "%*s %*s %*s %*s %*s %d", &n6);
fprintf(op2, "%d\n", n6); // Writes only the column 6th of out to out2 file
}
// Stores the value in last line, 6th column in variable "l"
{
while (fgets(line2, sizeof(line2), ip) !=0)
if ((pch2 = strstr (line2, c)) != NULL)
{
strcpy(lastline, line2);
}
}
fclose(ip);
if(*lastline)
{
strtok(lastline," "); //skip first field
int i =0;
for(i=0;i<4;i++) // skip next 4 fields (5 in total)
strtok(NULL," ");
sscanf(strtok(NULL," "),"%d",&l);
printf("Number of residues: %d\n", l); //print the 6th field
}
fclose(op2);
return 0;
}
如果有人指出我哪里弄错了,我会很感激的 这个程序有很多问题,你有。但是,您看到的错误
分段错误
是由于您提到的sscanf()
- 在理想情况下,您还需要在中检查
EOF
的返回值fgets()
- 您还可以将
写成sscanf()
sscanf(第行,“%s%s%s%s %d“、n1和n2、n3和n4、n5和n6)代码>您可能希望捕获所有5个字符串。及 当然,在使用之前,您需要先定义变量
n1、n2….、n5
分段错误
将不再困扰您。我希望这将帮助你最终纠正你的程序
更新:
刚才我在看你的另一篇文章时意识到,你不想从
文件中读取5个字符串,然后读取一个整数。您可能希望按顺序读取字符串整数...
。因此,您需要使用sscanf(行“%s%d%s%s%d”、&n1、&n2、&n3、&n4、&n5、&n6)
读取所需值并存储在相应变量中后,您只能在需要时使用n6
。您可以选择不使用的其余变量。您需要检查sscanf
调用的返回,以确保实际获得所需的转换次数(例如int cnv;cnv=sscanf(第3行,“%*s%*s%*s%*s%*s%*s%d”、&n6);如果(!cnv)…
我怀疑你碰到了一个空行或类似的问题,n6
不是你想象的那样。
while (fgets(line3, sizeof(line3), ip) != 0)
{
sscanf(line3, "%*s %*s %*s %*s %*s %d", &n6);
fprintf(op2, "%d\n", n6); // Writes only the column 6th of out to out2 file
}