一开始用fopen 读取文件的时候 总是返回Null
Can't open (null) for reading. 原因是最后一个参数后面有“\n”
对于fasta序列有多行的情况,需要把字符串连接, 这在perl 或 python里面都比较容易实现;
在C里面也可以实现, 有个strcat函数, 这里还有一种方法是自定义连接字符串的函数
例一
#include#include #include #include #define LINE 4096void rtrim(char *str){ char *s; s = str + strlen(str); while (--s >= str) { if (!isspace(*s)) break; *s = 0; }}int main(int argc, char * argv[]){ void rtrim(char *str); FILE *in; char *T1 = (char*)malloc(sizeof(char) *LINE); int i, a, seq_len, seq_number = 0; char fa[10240] = ""; for (i = 1; i < argc; i++){ printf("%s\n",argv[i]); rtrim(argv[i]); in = fopen(argv[i], "r"); if ( in == NULL){ printf ("Can't open %s for reading.\n", argv[i]); return 1; } while(!feof(in)){ fgets(T1, LINE, in); if (T1[0] != '>' ){ rtrim(T1); strcat(fa, T1); } else { seq_number ++; if(seq_number > 1){ printf("%s\n",fa); } printf ("%s",T1); memset(fa,0, 10240); } } printf("%s\n",fa); fclose(in); free(T1); } return 0;}
例二
#include#include #include #include #define LINE 4096void rtrim(char *str){ char *s; s = str + strlen(str); while (--s >= str) { if (!isspace(*s)) break; *s = 0; }}void concatStr(char *a, char *b){ while(*a++); a--; while((*a++ = *b++)!='\0');}int main(int argc, char * argv[]){ void rtrim(char *str); void concatStr(char *a, char*b); FILE *in; char *T1 = (char*)malloc(sizeof(char) *LINE); int i, a, seq_len, seq_number = 0; char *pfa = (char*)malloc(sizeof(char) * 10240); for (i = 1; i < argc; i++){ printf("%s\n",argv[i]); rtrim(argv[i]); in = fopen(argv[i], "r"); if ( in == NULL){ printf ("Can't open %s for reading.\n", argv[i]); return 1; } while(!feof(in)){ fgets(T1, LINE, in); if (T1[0] != '>' ){ rtrim(T1); concatStr(pfa, T1); } else { seq_number ++; if(seq_number > 1){ printf("%s\n",pfa); } printf ("%s",T1); memset(pfa,0, 1024); } } printf("%s\n",pfa); fclose(in); free(T1); free(pfa); } return 0;}
两个共同点是 都要用memset对指针清零, 不同点是第一个不用free(), 第二个要用free()释放内存