gpt4 book ai didi

C编程: How to extract a particular column from an input file and store in an array

转载 作者:行者123 更新时间:2023-11-30 18:15:19 25 4
gpt4 key购买 nike

我想将输入文件“out”第 6 列的整数值存储在一个数组中,以便我可以对其进行进一步的操作。

以下是我编写的用于将输入文本文件中的值放入数组的代码,但它没有指定第 6 列中的值:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len = 0;
char line[1000];
char line2[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.");
exit(1);
}
else
{
while (fgets(line, sizeof(line), fp) != 0)
{
if((pch = strstr (line, c))!= 0)
fprintf(op, "%s\n", line);
}
}
fclose(fp);
fclose(op);
FILE *ip = fopen("out", "r");
int numberArray[500];
int i;

for (i = 0; i < 500; i++)
{
fscanf(ip, "%1d", &numberArray[i]);
}

for (i = 0; i < 500; i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}

fclose(ip);
}

以下是我的输入文件:

ATOM      1  N   MET A   1      12.969  18.506  30.954  1.00 15.93           N  

ATOM 2 CA MET A 1 13.935 18.529 29.843 1.00 17.40 C

ATOM 3 C MET A 1 13.138 18.692 28.517 1.00 14.65 C

ATOM 4 O MET A 1 12.007 18.222 28.397 1.00 13.04 O

ATOM 5 CB MET A 1 14.733 17.216 29.882 1.00 20.72 C

ATOM 6 CG MET A 1 15.742 16.983 28.738 1.00 23.81 C

ATOM 7 SD MET A 1 17.378 17.025 29.359 1.00 28.11 S

ATOM 8 CE MET A 1 17.166 16.055 30.819 1.00 27.51 C

ATOM 9 N THR A 2 13.719 19.413 27.573 1.00 12.63 N

ATOM 10 CA THR A 2 13.088 19.661 26.283 1.00 12.68 C

ATOM 11 C THR A 2 13.561 18.631 25.300 1.00 12.02 C

ATOM 12 O THR A 2 14.763 18.432 25.121 1.00 13.07 O

ATOM 13 CB THR A 2 13.527 20.980 25.667 1.00 14.62 C

ATOM 14 OG1 THR A 2 13.307 22.020 26.627 1.00 15.31 O

ATOM 15 CG2 THR A 2 12.704 21.284 24.409 1.00 14.47 C

ATOM 16 N TYR A 3 12.574 18.048 24.642 1.00 11.17 N

我的问题是我需要对此代码进行哪些更改才能仅提取第 6 列并将其放入数组中。提前致谢。

最佳答案

从您之前@BLUEPIXY评论的帖子开始,即C program: Error reading and printing a particular column from a text file

在开头

op=fopen("out.bin","wb");//open a new binary file in write mode 

然后

//fprintf(op, "%d\n", n6); remove this
fwrite(&n6,sizeof(n6),1,op);// replace it by this

最后

fclose(op); // close the output file
op=fopen("out.bin","rb");//reopen it in read mode
fsseek(op,0,SEEK_END);
int len=ftell(op); // get file size in bytes
fsseek(op,0,SEEK_SET);//rewind to 0;

int *arr=malloc(len);//WARNING: error checking omitted
fread(arr,len,1,op); //load all content in array
fclose(fp);

len/=sizeof(int); //len of array
for(int i=0;i<len;i++)
printf("%d",arr[i]); //print content

//when done free memory
free(arr);

关于C编程: How to extract a particular column from an input file and store in an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com