【问题标题】:Read only one file, and write only another with open()只读一个文件,用 open() 只写另一个
【发布时间】:2019-04-27 08:20:12
【问题描述】:

我只需要读取一个文件并只写入另一个文件。

我试着写了一些代码,但是有很多错误。

我来了:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int f_open(const char *name);
int f_write(const char *name, int oflag, mode_t mode);


int f_open(const char *name){
   int dskr;
   dskr = open( name, O_RDONLY );
   if( dskr == -1 ){
      perror( name );
      exit(1);
   }
   printf( "dskr = %d\n", dskr );
   return dskr;
}

int f_write(const char *name, int oflag, mode_t mode){
   int dskr;
   dskr = write( name, O_WRONLY | O_CREAT | O_TRUNC, 0644 );
   if( dskr == -1 ){
      perror( name );
      exit(1);
   }
   printf( "dskr = %d\n", dskr );
   return dskr;
}

int main( int argc, char *argv[] ){
   int d;
   int f;
   if( argc != 2 ){
      printf( "Naudojimas:\n %s failas_ar_katalogas\n", argv[0] );
      exit( 255 );
   }
   d = f_open( argv[1] );
   f = f_write( argv[2] );
   return 0;
}

我得到的都是错误:

edgals_rw01.c: In function ‘f_write’:
edgals_rw01.c:29:4: warning: passing argument 1 of ‘write’ makes integer from pointer without a cast
/usr/include/unistd.h:532:16: note: expected ‘int’ but argument is of type ‘const char *’
edgals_rw01.c:29:4: warning: passing argument 2 of ‘write’ makes pointer from integer without a cast
/usr/include/unistd.h:532:16: note: expected ‘const void *’ but argument is of type ‘int’
edgals_rw01.c: In function ‘main’:
edgals_rw01.c:54:4: error: too few arguments to function ‘f_write’
edgals_rw01.c:27:5: note: declared here

【问题讨论】:

  • f_write() 中存在参数不匹配,因为编译器报告正确。将int f_write(const char *name, int oflag, mode_t mode); 更改为int f_write(const char *name);,因为无论如何您都没有在f_write() API 中使用收到的offlagmode
  • f_write 应该做什么?写入文件还是打开文件?你打电话给write,因为它是open。也许是时候回到您的书籍或教程,阅读更多关于openwrite 电话的信息了?或者获得一本书或找一个教程?
  • @Achal 但我需要如果该文件不存在则应该只读创建,如果存在则清除其中的数据。

标签: c unix compiler-errors file-descriptor


【解决方案1】:

只听你的编译器:

  • write() 系统调用采用文件描述符(具有int 类型) - 而不是文件名。但是您尝试使用name 调用它。
  • 你的f_write() 函数有两个它没有使用的参数——标志和打开模式;您实际上是在将它们设置为固定值 - 所以只需删除这些参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多