A solution for Project Five
Below is the listing for a possible solution to the project.
/* MCS 275 Project Five: Recording Temperatures */
#include <stdio.h>
#include <string.h>
void logtemp ( FILE *fp );
/* logs temperatures for cities given on input */
int search ( FILE *fp, char *s );
/* return 1 if string found in the file */
int main ( int argc, char *argv[] )
{
FILE *fp;
if (argc < 2)
{
printf("Need one file as argument. Please try again...\n");
exit(1);
}
else
{
fp = fopen(argv[1],"r");
if (fp == NULL)
fp = fopen(argv[1],"w");
else
{
fclose(fp);
fp = fopen(argv[1],"r+");
}
logtemp(fp);
}
fclose(fp);
return 0;
}
int search ( FILE *fp, char *s )
{
int i,okay;
int len = strlen(s);
char city[80];
char c;
for (;;)
{
for (i=0; i < len; i++)
{
okay = fscanf(fp,"%c", &city[i]);
if (city[i] == '\n') okay = 0;
if (okay == 0) break;
}
city[len] = '\0';
if (okay == 1)
if (strcmp(s,city) == 0)
return 1;
fscanf(fp,"%*[^\n]"); /* skip rest of line */
c = getc(fp); /* skip new line symbol */
if (c == EOF) break;
}
return 0;
}
void logtemp ( FILE *fp )
{
char city[80];
float t;
int found;
char c;
for (;;)
{
printf("Give name of city (enter to stop) : ");
city[0] = '\n';
scanf("%79[^\n]", city);
if (city[0] == '\n') break;
found = search(fp,city);
if (found == 0)
{
fprintf(fp,"%s", city);
printf("Give temperature in %s : ", city);
scanf("%f", &t);
fprintf(fp,"%8.1f\n", t);
}
else
{
fscanf(fp,"%f", &t);
printf("The current temperature in %s is %.1f\n", city, t);
printf("Give the new temperature in %s : ", city);
scanf("%f", &t);
fseek(fp,-8,1);
fprintf(fp,"%8.1f\n",t);
}
c = getchar(); /* skip new line symbol */
rewind(fp);
}
}