fputc无法将字符写入文件?

时间:2019-09-28 19:07:45

标签: c

编写一个程序,该程序使用fputc将单个字符写入文件,但字符未写入文件。我想念什么吗?

#include <stdio.h>
#include <stdlib.h>

int main (void)
{

    FILE *fpnt;
    char mychar;
    fpnt = fopen("/Users/name/Desktop/data.txt", "w");

    if(fpnt == NULL)
    {
    printf("Unable to open the file...");
    exit(0);
    }
    while((mychar = getchar()) != EOF)
    {
    fputc(mychar, fpnt);
    }
    fclose(fpnt);
}

1 个答案:

答案 0 :(得分:-3)

尝试此代码:

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

void ft_putchar_fd(char c, int fd)
{
    write(fd, &c, 1);
 }

int main (void)
{

int fd;
char mychar;
fd = open("/Users/name/Desktop/data.txt", O_RDWR);

if(fd == -1)
{
printf("Unable to open the file...");
exit(0);
}
while((mychar = getchar()) != EOF)
{
    ft_putchar_fd(mychar, fd);
}
close(fd);
}