日期:2014-05-16  浏览次数:20761 次

帮帮我用read函数一个简单的读取文本a.txt中的数据,保存到以下变量中//例子//
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
  fd = open("a.txt", O_WRONLY|O_CREAT|O_TRUNC);
  if(fd==-1)perror(""),exit(-1);
  char buf[100] = {};
  sprintf(buf, "%d", id);
  write(fd, buf, strlen(buf));
  write(fd, "\t", 1);
  write(fd, name, strlen(name));
  write(fd, "\t", 1);
  memset(buf, 0, sizeof(buf));
  sprintf(buf, "%d", age);
  write(fd, buf, strlen(buf));
  write(fd, "\t", 1);
  memset(buf, 0, sizeof(buf));
  sprintf(buf, "%g", salary);
  write(fd, buf, strlen(buf));
  close(fd);
  //----读取文本a.txt中的数据,保存到以下变量中-----
  int rid2;
  char rname2[20];
  int rage2;
  double rsalary2;
  /*
  // atoi
  // atof
  */
}

------解决方案--------------------
這麼簡單不需要大神出手,我來吧!
樓主結貼要及時哦~
C/C++ code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    int fd = open("a.txt", O_WRONLY | O_CREAT | O_TRUNC);
    if (fd == -1)
        perror(""), exit(-1);
    char buf[100] = {0};
    
    /* define variables first */
    int id = 3;
    char *name = "XX不哭,站起來擼!";
    int age = 23;
    double salary = 8700.29;    /* Chinese Yuan */

    sprintf(buf, "%d\t%s\t%d\t%g", id, name, age, salary);
    write(fd, buf, sizeof(buf));
    close(fd);
    
    /* 變量不定義在開始是C99支持的寫法,如果用gcc編譯器記得加“-std=c99”*/
    int rid2;
    char rname2[20];
    int rage2;
    double rsalary2;

    char id2[20], age2[20], salary2[20];
    
    if((fd = open("a.txt", O_RDONLY)) < 0) {
        perror("");
        exit(1);
    }

    read(fd, buf, sizeof(buf));
    sscanf(buf, "%s\t%s\t%s\t%s", id2, rname2, age2, salary2);
    close(fd);

    rid2 = atoi(id2);
    rage2 = atoi(age2);
    rsalary2 = atof(salary2);

    printf("rid2: %d\n"
        "rname2: %s\n"
        "rage2: %d\n"
        "rsalary2: %g\n", rid2, rname2, rage2, rsalary2);

}