[ create a new paste ] login | about

Link: http://codepad.org/RGYxbuFY    [ raw code | fork ]

C, pasted on Jun 11:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define FILENAME "file1"
struct goods{
  char name[20];
  char price[5];
};

#if 1
int main() {
  struct goods record;
  FILE *fp;
  char name[20];
  int i, eof;

  if ((fp = fopen(FILENAME, "r+")) != 0) {
    eof = 0;
    printf("name?\n");
    scanf("%s",name);
    for (i = 0;;) {
      if (fread(&record, sizeof(record), 1, fp) != 1)
        eof = 1;
      if(strcmp(record.name, name) == 0){
        break;
      }
      if (eof)
        break;
      i++;
    }
    if (!eof) {
      printf("rec no=%d name=%s price=%s\n", i + 1, record.name, record.price);
      printf("Current price\t:%s\n",record.price);
      printf("New price?\t:");
      scanf("%s",record.price);
      fseek(fp, -sizeof(struct goods), SEEK_CUR);
      fwrite(&record, sizeof(struct goods), 1, fp);
      printf("update....ended\n");
    }
    fclose(fp);
  }
  return 0;
}
#else
int main() {
  FILE *fp;
  int i;
  static struct goods a[] = {
    { "abc", "123" },
    { "def", "456" },
    { "xyz", "987" }
  };
  if ((fp = fopen(FILENAME, "w")) != 0) {
    for (i = 0; i < sizeof(a) / sizeof(struct goods); i++) {
      printf("%d\n", i);
      fwrite(&a[i], sizeof(struct goods), 1, fp);
    }
    fclose(fp);
  }
  return 0;
}
#endif


Output:
No errors or program output.


Create a new paste based on this one


Comments: