
Scan line add array
By: a guest on
Apr 17th, 2012 | syntax:
C | size: 1.61 KB | hits: 20 | expires: Never
int fscanline(FILE *f, char *buffer) {
int c, i = 0;
while( c = getc(f) ) {
if( c == '\r' || c == '\n' || c == '\0' || c == EOF ) {
buffer[i] = '\0';
break;
}
buffer[i++] = c;
}
return i;
}
int updateCounters(char *buffer, int *c1, int *c2) {
int d, r = sscanf(buffer, "%d %d", &d, &d);
if( r == 1 ) {
(*c1)++;
}
if( r == 2 ) {
(*c2)++;
(*c1)++;
}
}
int fileDemo() {
int rowsCountOne = 0, rowsCountTwo = 0;
char buffer[512];
int *rowOne;
int *rowTwo;
int i = 0;
FILE *f = fopen("d:\\demo.txt", "r");
if( !f ) {
printf("Cannot open file\n");
return doExit();
}
while(fscanline(f, buffer)) {
int d1, d2, r = sscanf(buffer, "%d %d", &d1, &d2);
if( r == 2 ) {
rowsCountOne++;
rowsCountTwo++;
} else if ( r == 1 ) {
rowsCountOne++;
}
}
printf("%i %i\n", rowsCountOne, rowsCountTwo);
rowOne = (int*)malloc(rowsCountOne * sizeof(int));
rowTwo = (int*)malloc(rowsCountTwo * sizeof(int));
fseek(f, 0, 0);
rowsCountOne = 0;
rowsCountTwo = 0;
while(fscanline(f, buffer)) {
int d1, d2, r = sscanf(buffer, "%d %d", &d1, &d2);
if( r == 2 ) {
rowOne[rowsCountOne++] = d1;
rowTwo[rowsCountTwo++] = d2;
} else if ( r == 1 ) {
rowOne[rowsCountOne++] = d1;
}
}
for( i = 0; i < rowsCountOne; ++i ) {
printf("%i ", rowOne[i]);
} printf("\n");
for( i = 0; i < rowsCountTwo; ++i ) {
printf("%i ", rowTwo[i]);
} printf("\n");
free(rowOne);
free(rowTwo);
printf("\n\nOK LA\n");
doExit();
}
int main() {
fileDemo();
return 0;
}