Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created June 14, 2011 14:18
Show Gist options
  • Save kopiro/1024988 to your computer and use it in GitHub Desktop.
Save kopiro/1024988 to your computer and use it in GitHub Desktop.
Write row by file in a sequence of row
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROW_LENGTH 200
void printerr(char* msg) {
printf("\n%s\n", msg);
fflush(stdout);
#if defined (__WIN32__)
system("PAUSE");
#endif
exit(EXIT_FAILURE);
}
int main(int argc, const char* argv[]) {
char tablepath[20];
printf("Insert input table filename: ");
scanf("%s", tablepath);
FILE* tablefp = fopen(tablepath, "r");
if (tablefp==NULL) printerr("Unable to open file.");
char seqpath[20];
printf("Insert input sequence filename: ");
scanf("%s", seqpath);
FILE* seqfp = fopen(seqpath, "r");
if (seqfp==NULL) printerr("Unable to open file.");
char outpath[20];
printf("Insert output filename: ");
scanf("%s", outpath);
FILE* outfp = fopen(outpath, "w");
if (outfp==NULL) printerr("Unable to open file.");
char** table = malloc(sizeof(char*));
char* row = malloc(MAX_ROW_LENGTH*sizeof(char));
int size = 1;
while (!feof(tablefp)) {
fgets(row, MAX_ROW_LENGTH*sizeof(char), tablefp);
if (row==NULL) break;
table[size-1] = malloc((strlen(row)+1)*sizeof(char));
if (table[size-1]==NULL) printerr("Error while allocating memory for table.");
if (row[strlen(row)-1]=='\n') row[strlen(row)-1]='\0';
strcpy(table[size-1], row);
char** newtable = realloc(table, (++size)*sizeof(char*));
if (newtable==NULL) printerr("Error while increasing size memory for table.");
table = newtable;
}
free(row);
fclose(tablefp);
int n;
while (!feof(seqfp)) {
fscanf(seqfp, "%d", &n);
if (n>0 && n<=size) fprintf(outfp, "%s\n", table[n-1]);
}
fclose(seqfp);
fclose(outfp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment