简体   繁体   English

C-将输入数据写入文件

[英]C - write() input data to file

The user inputs, for 2 students, the name, ID, date of birth, gender and marital status. 用户为两名学生输入姓名,身份证,出生日期,性别和婚姻状况。 I should then write each input individually to a file. 然后,我应该将每个输入单独写入文件。 This is my code. 这是我的代码。

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
    int fd, i;
    char name[20], id[10], dob[10], gender[7], status[10];
    fd = open("lab45.txt", O_WRONLY|O_CREAT, S_IRWXU);
    for (i = 1; i < 3; i = i + 1)
    {
        printf("\n\nStudent %d", i);
        printf("\n-Name: ");
        scanf(" %[^\n]", name);
        printf("\n-ID: ");
        scanf("%s", id);
        printf("\n-Date of birth: ");
        scanf("%s", dob);
        printf("\n-Gender: ");
        scanf("%s", gender);
        printf("\n-Marital status: ");
        scanf("%s", status);
        write(fd, &name, 20);
        write(fd, &id, 10);
        write(fd, &dob, 10);
        write(fd, &gender, 7);
        write(fd, &status, 10);
    }
    close(fd);
}

I input the following: 我输入以下内容:

Student 1 学生1

-Name: John Smith -姓名:约翰·史密斯

-ID: JS3019 -ID:JS3019

-Date of birth: 14/10/90 -出生日期:14/10/90

-Gender: male -性别:男

-Marital status: single -婚姻状况:单身

Student 2 学生2

-Name: Jane Doe -名称:Jane Doe

-ID: JD0192 -ID:JD0192

-Date of birth: 13/12/99 -出生日期:99/12/13

-Gender: female -性别女

-Marital status: married -婚姻状况:已婚

This is what I see in the text file afterwards. 这就是我随后在文本文件中看到的内容。

John Smith\\00\\00\\00\\00\\00\\00\\A0@\\00JS3019\\00\\00\\C0\\F414/10/90\\00\\00male\\00\\00\\00single\\00\\00\\EDJane Doe\\00h\\00\\00\\00\\00\\00\\00\\A0@\\00JD0192\\00\\00\\C0\\F413/12/99\\00\\00female\\00married\\00\\ED 约翰·史密斯\\ 00 \\ 00 \\ 00 \\ 00 \\ 00 \\ 00 \\ A0 @ \\ 00JS3019 \\ 00 \\ 00 \\ C0 \\ F414 / 10/90 \\ 00 \\ 00male \\ 00 \\ 00 \\ 00单\\ 00 \\ 00 \\ EDJane Doe \\ 00h \\ 00 \\ 00 \\ 00 \\ 00 \\ 00 \\ 00 \\ A0 @ \\ 00JD0192 \\ 00 \\ 00 \\ C0 \\ F413 /九十九分之一十二\\ 00 \\ 00female \\ 00married \\ 00 \\ ED

Is this normal or there is something wrong in my code? 这是正常现象还是我的代码有问题?

The problem you see is the result of writing the entire arrays to the file rather than just the parts containing data. 您看到的问题是将整个数组而不是仅包含数据的部分写入文件的结果。 You can either: 您可以:

  1. Use fprintf to print string data to the file rather than using write : 使用fprintf将字符串数据打印到文件中,而不是使用write

     FILE *f = fdopen(fd, "w"); fprintf(f, "%s", name); 
  2. Change the length value you pass to write to include only the used data: 更改传递给write的长度值,使其仅包含已使用的数据:

     write(fd, &name, strlen(name)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM