c - 从 C 中的文件加载数据

标签 c database

我正在创建一个简单的 C 程序 - 员工数据库...我的数据存储在 .txt 文件中,用逗号和\n 分隔,所以它看起来像这样:

data1,id1,name1

data2,id2,name2

从文件加载所有数据并将每个值保存为自变量(例如 p->data、p->id、p->name)的最佳方法是什么(在 C 中,而不是 C++ 中)?

这是我用来将数据存储到变量中的代码(不是存储到文件中,变量仅用于脚本):

    void insert(emp *p,int n)
{
  p=p+n;
  printf("\nenter name of emplyee:");
  _flushall();
  gets(p->name);
  printf("\nenter employee id:");
  scanf("%d",&p->empid);
  printf("\nenter salary of the emplyee:");
  scanf("%d",&p->salary);
  printf("\nenter phone no of the emplyee:");
  flushall();
  gets(p->ph);
}

此脚本将数据保存到文件中:

void sejv(emp *p,int n)
{
      int i;
        FILE *fptr;
    fptr=fopen("ulozka.txt","w+");
    if(fptr==NULL){
      printf("Error opening file!");   
      getchar();             
   }
  printf("Ukladani...");
  for(i=0;i<n;i++)
  {
   fprintf(fptr,"%d,%s,%d,%s\n",p->empid,p->name,p->salary,p->ph);   

    p=p+1;
  }

   fclose(fptr);
   exit(0);
 }

我需要的只是将数据加载到主函数中,以便我可以使用它。

编辑: 我正在添加其余的代码:

typedef struct employee
{
  char name[20],ph[20];
  int empid,salary;
}emp;

void main()
{
  emp e;
  emp *p;
  int n=0,ch;
  p=&e;
}

以及我需要创建的函数中的“某些东西”...

void nacti(emp *p,int n)
{
      int i;
        FILE *fptr;
    fptr=fopen("ulozka.txt","r");
    if(fptr==NULL){
      printf("Error opening file!");   
      getchar();             
   }
 printf("Nacitani...");

//loading function
      p=p+n;
   fscanf(fptr,"%d,%[^\,],%d,%s", &p->empid, p->name, &p->salary,p->ph);
   printf("%s", p->name);


 }

我需要一个函数,可以按列和行从txt文件中读取数据(一个循环,将第一行的数据添加到p中,然后将p的值增加1,从第二行插入数据等等...)

感谢您的建议...

最佳答案

检查下面的代码,它可以完成如下所示的广告:

struct data
{
    int index;
    int id;
    char name[30];
};

int main ()
{
    struct data p[3];
    int i=0;
FILE *fp = fopen("input.txt","r+");
while(fscanf(fp,"%d,%d,%s",&p[i].index,&p[i].id,p[i].name) != EOF)
{
    i++;
}
i=0;
while(i<3)
{
fprintf(fp,"%d %d %s\n",p[i].index,p[i].id,p[i].name);
i++;
}
fclose(fp);
}

关于c - 从 C 中的文件加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892946/

相关文章:

c++ - 将内存数据库保存到磁盘

mysql - 我可以在MySQL数据库的列中输入公式吗?

c++ - OS X 上的 OpenMP 汇编程序错误

database - 在 SQLite 中按 rowid 排序保证很快

mysql-无法添加外键约束

python - 如何查看数据导入是否成功

c - C中的按位运算问题

c - Visual Studio C2085 关于数组定义

c - 如何轻松获取 union 的活跃值(value)?

c++ - 在 C/C++ 中,int (*f) (float *) 会创建什么?