我是一名生物学学生,我正在尝试学习perl,python和C,并在我的工作中使用这些脚本。所以,我有一个文件如下:
>sequence1
ATCGATCGATCG
>sequence2
AAAATTTT
>sequence3
CCCCGGGG
输出应如下所示,即每个序列的名称和每行中的字符数,并打印文件末尾的序列总数。
sequence1 12
sequence2 8
sequence3 8
Total number of sequences = 3
我可以让perl和python脚本工作,这是python脚本的一个例子:
#!/usr/bin/python
import sys
my_file = open(sys.argv[1]) #open the file
my_output = open(sys.argv[2], "w") #open output file
total_sequence_counts = 0
for line in my_file:
if line.startswith(">"):
sequence_name = line.rstrip('\n').replace(">","")
total_sequence_counts += 1
continue
dna_length = len(line.rstrip('\n'))
my_output.write(sequence_name + " " + str(dna_length) + '\n')
my_output.write("Total number of sequences = " + str(total_sequence_counts) + '\n')
现在,我想在C中编写相同的脚本,这是我到目前为止所取得的成就:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
input = FILE *fopen(const char *filename, "r");
output = FILE *fopen(const char *filename, "w");
double total_sequence_counts = 0;
char sequence_name[];
char line [4095]; // set a temporary line length
char buffer = (char *) malloc (sizeof(line) +1); // allocate some memory
while (fgets(line, sizeof(line), filename) != NULL) { // read until new line character is not found in line
buffer = realloc(*buffer, strlen(line) + strlen(buffer) + 1); // realloc buffer to adjust buffer size
if (buffer == NULL) { // print error message if memory allocation fails
printf("\n Memory error");
return 0;
}
if (line[0] == ">") {
sequence_name = strcpy(sequence_name, &line[1]);
total_sequence_counts += 1
}
else {
double length = strlen(line);
fprintf(output, "%s \t %ld", sequence_name, length);
}
fprintf(output, "%s \t %ld", "Total number of sequences = ", total_sequence_counts);
}
int fclose(FILE *input); // when you are done working with a file, you should close it using this function.
return 0;
int fclose(FILE *output);
return 0;
}
但是这段代码当然充满了错误,我的问题是尽管经过了很多研究,我仍然无法正确理解和使用内存分配和指针,所以我知道我特别在那部分有错误。如果你可以对我的代码发表评论并看看它如何变成一个真正有效的脚本,那就太好了。顺便说一句,在我的实际数据中,每行的长度没有定义,所以我需要为此目的使用malloc和realloc。
答案 0 :(得分:3)
对于像这样的简单程序,你一次看一个短行,你不应该担心动态内存分配。使用合理大小的本地缓冲区可能已经足够了。
另一件事是C不是特别适合快速和脏的字符串处理。例如,标准库中没有strstrip
函数。您通常最终会自己实施此类行为。
示例实现如下所示:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
char line[MAXLEN]; /* Current line buffer */
char ref[MAXLEN] = ""; /* Sequence reference buffer */
int nseq = 0; /* Sequence counter */
if (argc != 3) {
fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
exit(1);
}
in = fopen(argv[1], "r");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s.\n", argv[1]);
exit(1);
}
out = fopen(argv[2], "w");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s for writing.\n", argv[2]);
exit(1);
}
while (fgets(line, sizeof(line), in)) {
int len = strlen(line);
/* Strip whitespace from end */
while (len > 0 && isspace(line[len - 1])) len--;
line[len] = '\0';
if (line[0] == '>') {
/* First char is '>': copy from second char in line */
strcpy(ref, line + 1);
} else {
/* Other lines are sequences */
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
许多代码都是关于强制执行参数以及打开和关闭文件。 (如果您使用stdin
和stdout
进行文件重定向,则可以删除大量代码。)
核心是大while
循环。注意事项:
fgets
在出错时或到达文件末尾时返回NULL
。 '\0'
终止剥离的字符串">"
是由两个字符'>'
和终止'\0'
组成的字符串文字。int
,但由于某行中的字符数不能为负数,因此使用无符号类型可能会更好。)line + 1
相当于&line[1]
。对于初学者来说,跟踪这一点可能相当多。对于像你这样的小型文本处理任务,Python和Perl肯定更适合。
编辑:上面的解决方案不适用于长序列;它仅限于MAXLEN
个字符。但如果您只需要长度而不需要序列的内容,则不需要动态分配。
这是一个不读取行的更新版本,而是读取字符。在'>'
上下文中,它存储了引用。否则它只是保持计数:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h> /* for isspace() */
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
int nseq = 0; /* Sequence counter */
char ref[MAXLEN]; /* Reference name */
in = fopen(argv[1], "r");
out = fopen(argv[2], "w");
/* Snip: Argument and file checking as above */
while (1) {
int c = getc(in);
if (c == EOF) break;
if (c == '>') {
int n = 0;
c = fgetc(in);
while (c != EOF && c != '\n') {
if (n < sizeof(ref) - 1) ref[n++] = c;
c = fgetc(in);
}
ref[n] = '\0';
} else {
int len = 0;
int n = 0;
while (c != EOF && c != '\n') {
n++;
if (!isspace(c)) len = n;
c = fgetc(in);
}
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
注意:
fgetc
从文件中读取单个字节,并在文件结束时返回此字节或EOF
。在这个实现中,这是唯一使用的阅读功能。fgetc
存储参考字符串。您也可以在跳过初始尖括号后使用fgets
。n
是总计数,len
是最后一个非空格的计数。 (您的行可能只包含ACGT,没有任何尾随空格,因此您可以跳过测试空间并使用n
代替len
。)答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
FILE *my_file = fopen(argv[1], "r");
FILE *my_output = fopen(argv[2], "w");
int total_sequence_coutns = 0;
char *sequence_name;
int dna_length;
char *line = NULL;
size_t size = 0;
while(-1 != getline(&line, &size, my_file)){
if(line[0] == '>'){
sequence_name = strdup(strtok(line, ">\n"));
total_sequence_coutns +=1;
continue;
}
dna_length = strlen(strtok(line, "\n"));
fprintf(my_output, "%s %d\n", sequence_name, dna_length);
free(sequence_name);
}
fprintf(my_output, "Total number of sequences = %d\n", total_sequence_coutns);
fclose(my_file);
fclose(my_output);
free(line);
return (0);
}