读书人

帮帮小弟我用read函数一个简单的读取文

发布时间: 2012-03-21 13:33:15 作者: rapoo

帮帮我用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);} 

读书人网 >UNIXLINUX

热点推荐