If you want to use files, then do something like the following. A more effecient approach would keep everything in memory, but this may not be what you want. Also note that '\n' can become different character combinations on different systems, so I modified your original code to use (char)10 as the row seperator.
One final warning: the following code does only what you asked, it is not effecient at all, and should never be used in any time critical code, or in any code where changeSeat is called regularly (or where the database is large).
#include <stdio.h>
#define SEATS_DATABASE "seats.db"
#define NUM_ROWS 8
#define NUM_SEATS 8
void initDataBase(void)
{
FILE *fp;
int i;
int j;
fp = fopen(SEATS_DATABASE, "w");
if(fp == NULL)
{
printf("Can't create file");
exit(0);
}
else
{
for(i=0; i<NUM_ROWS; ++i)
{
for(j=0; j<NUM_SEATS; ++j)
fputc('X', fp);
if(i != NUM_ROWS-1)
fputc(10, fp);
}
fclose(fp);
}
}
void changeSeat(int row, int seat, char ch)
{
FILE* fp;
fp = fopen(SEATS_DATABASE, "r+");
if (fp)
{
fseek(fp, row*(NUM_SEATS+1)+seat, SEEK_SET);
fputc(ch, fp);
fclose(fp);
}
else
{
printf("Can't update the database\n");
}
}
int main(void)
{
initDataBase();
changeSeat(3, 3, 'O');
changeSeat(0, 1, 'O');
return 0;
}
- #include <stdio.h>
- #define SEATS_DATABASE "seats.db"
- #define NUM_ROWS 8
- #define NUM_SEATS 8
- void initDataBase(void)
- {
- FILE *fp;
- int i;
- int j;
- fp = fopen(SEATS_DATABASE, "w");
- if(fp == NULL)
- {
- printf("Can't create file");
- exit(0);
- }
- else
- {
- for(i=0; i<NUM_ROWS; ++i)
- {
- for(j=0; j<NUM_SEATS; ++j)
- fputc('X', fp);
- if(i != NUM_ROWS-1)
- fputc(10, fp);
- }
- fclose(fp);
- }
- }
- void changeSeat(int row, int seat, char ch)
- {
- FILE* fp;
- fp = fopen(SEATS_DATABASE, "r+");
- if (fp)
- {
- fseek(fp, row*(NUM_SEATS+1)+seat, SEEK_SET);
- fputc(ch, fp);
- fclose(fp);
- }
- else
- {
- printf("Can't update the database\n");
- }
- }
- int main(void)
- {
- initDataBase();
- changeSeat(3, 3, 'O');
- changeSeat(0, 1, 'O');
- return 0;
- }