LINUX系统调用open、write等完成从键盘中输入10个学生的有关数据,然后把他们转存到磁盘文件中,不用fopen和fread

写出来的的代码有一个问题就是,不能输入10个学生的数据,只能输入10个字符,想改成二维数组,strlen那里又会报错,九敏~


#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<iostream>
using namespace std;

int main(){
int fd;
int i;
fd=open("./file2",0_RDWR);
char msg[10] = {0};
for(i=0;i<10;i++)
{
  cin>>msg[i];
}
write(fd,msg,strlen(msg));
close(fd);
return 0;
}

这样操作,你看一下


#include<stdio.h>
#define SIZE 10
struct Student_type
{
    char name[10];
    int num;
    int age;
    char addr[15];
}stud[SIZE];
void save()
{
    FILE * fp;
    int i;
    if((fp = fopen("stu.dat", "wb")) == NULL)
    {
        printf("cannot open file\n");
        return;
    }
    for(i = 0; i < SIZE; i++)
        if(fwrite(&stud[i], sizeof(struct Student_type), 1, fp) != 1)
        printf("file write error\n");
    fclose(fp);
}
int main()
{
    int i;
    printf("Please enter data of students: \n");
    for(i = 0; i < SIZE; i++)
        scanf("%s%d%d%s", stud[i]. name, &stud[i]. num, &stud[i]. age, stud[i]. addr);
        save();
        return 0;
}