c - Writing and reading from a file and sort them in ascending order -
#include<stdio.h> void sort(int *p, int size) { int i, j; (i = 0; < size - 1; ++i) { (j = 0; j < size - - 1; ++j) { if (p[j] > p[j + 1]) { int temp; temp = p[j]; p[j] = p[j + 1]; p[j + 1] = temp; } } } } void createtestfile() { file *f1; f1 = fopen("program.txt", "w"); fprintf(f1, "6#this comment\n"); fprintf(f1, "3#this comment\n"); fprintf(f1, "7#this comment\n"); fprintf(f1, "2\n"); } void readtestfile() { file *fp; char buff[1024]; int value; int number_of_lines; fp = fopen("program.txt", "r"); { fgets(buff, 1024, fp); fscanf(fp, "%d", &value); number_of_lines++; buff[number_of_lines] = value; } while (fp != eof); sort(buff, number_of_lines); int i; (i = 1; < number_of_lines; i++) { printf("value %d", buff[i]); } } int main() { createtestfile(); readtestfile(); return 0; }
i writing string file. later reading integers file , sort them in ascending order. using fgets reading line line file , have problem in reading integers file.
you missing close file after having written it.
due content propably written when application end, because clsoed implicitly.
add
fclose(f1)
after last fprintf()
in createtestfile()
.
secondly when reading file should decide whether use fgets()
of fscanf()
read in data.
or can switch reading file directly using fscanf()
sscanf()
"string" read using fgets()
.
to replace
fscanf(fp, "%d", &value);
with
sscanf(buff, "%d", &value);
thirdly makes no sense try write scanned in buff
buff
, @ least because overwriting buff
in next round of read-loop.
also pass buff
sort()
should make compiler yell out loud warning.
initialise loop counter number_of_lines
0
and use integer array store values scanned out of file's content. can pass sort()
.
Comments
Post a Comment