【问题标题】:unable to write into file using c , with unix system calls无法使用 c 写入文件,带有 unix 系统调用
【发布时间】:2013-09-10 10:49:00
【问题描述】:

我正在处理unix system calls。 我想使用read()standard input读取string,然后使用write()将其写入文件。

我可以open 文件,read 来自standard inputstring,但无法write 将其发送到文件。

我的代码是:

#include <unistd.h>     // to remove WARNINGS LIKE  warning: implicit declaration of       function ‘read’ , warning: implicit declaration of function ‘write’
#include<fcntl.h>         /* defines options flags */
#include<sys/types.h>     /* defines types used by sys/stat.h */
#include<sys/stat.h>      /* defines S_IREAD & S_IWRITE  */
#include<stdio.h>

int main(void)
 {
 int fd,readd;
 char *buf[1024]; 


    fd = open("myfile",O_RDWR);
    if(fd != -1)
         printf("open error\n");
    else
    {
        // read i\p from stdin , and write it to myfile.txt

            if((readd=read(0,buf,sizeof(buf)))<0)
              printf("read error\n");
            else
             {
                    printf("\n%s",buf);
                    printf("\n%d",readd);
                if(write(fd,buf,readd) != readd)
                      printf("write error\n");

              }
    } 

return 0;
}

输出是

    write error

如果我 write stringstandard output,它工作正常

问题:

1) write() 有什么问题?

2) 我想在行尾包含换行符\n。怎么可能通过standard input

【问题讨论】:

  • 你可能想要char buf[1024],而不是char *buf[1024]
  • 检查errno变量。
  • 代替printf("write error"),使用perror("write")之类的东西。这会告诉你发生了哪个错误。
  • 它给了我错误 Bad file descriptor ,这意味着这些 file descriptor 无效,但是先生该怎么办?我不给file descriptor
  • 下面提到的所有事情,都已更正。但它仍然没有写我在standard input 中写的内容,它写的是kkcmvdksvdslvdvldzvd

标签: c unix


【解决方案1】:
fd = open("myfile",O_RDWR);

这将打开一个现有文件。如果该文件不存在,则会出现错误。 您可以使用 perror() 获取更多错误描述。

fd = open("myfile",O_RDWR);
if (fd == -1) {
   perror("open failed");
   exit(1);
}

这里的错误是你的错误检查逻辑错误。

if(fd != -1)
     printf("open error\n");

应该是

if(fd == -1)
     printf("open error\n"); //or better yet, perror("open error");

修正后,如果文件不存在,您在打开文件时仍会出现错误。要创建该文件,您还需要一个附加标志,并为其赋予适当的权限:

fd = open("myfile",O_RDWR|O_CREAT, 0664);

【讨论】:

    【解决方案2】:
    if(fd != -1)
         printf("open error\n");
    

    这看起来不对。如果您的输出不是“打开错误”,则可能意味着您对open 的调用失败,因为您仅在打开文件失败时才尝试写入文件。

    一个好主意是在打印错误时打印 errno,将错误打印到 stderr,而不是 stdout,并在出错时立即退出。尝试使用perror 打印错误消息。

    另外,我不喜欢这个评论:

    #include <unistd.h>     // to remove WARNINGS LIKE  warning: implicit declaration of       function ‘read’ , warning: implicit declaration of function ‘write’
    

    “删除警告”不需要包含。它需要使您的程序正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多