/* * Code example for CP264 Data Structures II * read formated data from file using fopen(), fclose() and fscanf() * HBF */ #include int main (){ char str[80]; float f; FILE *fp; fp = fopen("test.txt","w+"); if (fp == NULL) { perror("Error opening file"); return 0; } fprintf(fp, "%f %s", 3.14, "PI"); // write to file rewind(fp); // move the pointer to the beginning // fscanf(fp, "%f", &f); // formatted read from file // fscanf(fp, "%s", str); // read a string, formatted read from file fscanf(fp,"%f %s", &f, str); // read float string, // fscanf(fp,"%s %f", str, f); is normally not work, except for fixed length string fclose(fp); printf("%f and %s are added.\n", f, str); return 0; }