C写的()函数不工作 [英] C write() function not working

查看:114
本文介绍了C写的()函数不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写入一个文件,但它不工作。我可以打开一个文件,但在使用写函数在文件中写,TT书面方式是在标准输出本身,我打开文件的内容保持不变。

 #包括LT&;&stdio.h中GT;
#包括LT&; SYS / file.h>
#包括LT&; SYS / types.h中>
#包括LT&; SYS / stat.h>
#包括LT&;&limits.h中GT;
#包括LT&;&fcntl.h GT;
#包括LT&;&stdlib.h中GT;
#包括LT&; SYS / uio.h>
主(){
  CHAR FN [30];
  INT FD I = 0;
  诠释actualbytes,bytesstored;
  炭缓冲器[100];  的printf(\\ n输入带路径的文件名);
  scanf函数(%S,FN);  如果(FD =打开(FN,O_WRONLY | O_CREAT,S_IWUSR | S_IWUSR)℃下)
  {
     PERROR(开放);
     出口(0);
  }
  其他
  {
    写(标准输出,\\ n \\ n输入的文件\\ n内容);
    写(标准输出,preSS CTRL + D在文件\\ n \\ n的结尾);    fflush(标准输出);
    而((缓冲[I] = GETC(标准输入))= EOF!)我++;    缓冲[I] ='\\ 0';
    bytesstored = sizeof的(缓冲);    如果(actualbytes =写入(FD,缓冲器,bytesstored)℃的)
    {
       PERROR(写);
       出口(0);
    }
    其他
    {
       写(标准输出,\\ n \\ nfile的成功打开了);       写(标准输出,\\ n该内容将被写入); fflush(标准输出);
    }
    如果(接近(FD)℃,)
    {
       PERROR(亲密);
       出口(0);
    }
    其他
       的printf(\\ nfile的关闭);
 }
}


解决方案

< 具有较高的precedence比 =

  IF((FD =打开(FN,O_WRONLY | O_CREAT,S_IWUSR | S_IWUSR))小于0)

I am trying to write into a file, but it is not working. I can open a file, but while writing in the file using write function, tt is writting in the stdout itself, and the content of the file I opened remain unchanged.

#include<stdio.h>
#include<sys/file.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<limits.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/uio.h> 
main() {  
  char fn[30]; 
  int fd,i=0; 
  int actualbytes,bytesstored; 
  char buffer[100];

  printf("\nEnter the filename with path"); 
  scanf("%s",fn); 

  if(fd=open(fn,O_WRONLY|O_CREAT,S_IWUSR|S_IWUSR)<0) 
  {  
     perror("open"); 
     exit(0); 
  } 
  else 
  {
    write(stdout,"\n\nEnter the contents for the file\n");  
    write(stdout,"press CTRl+D at the end of the file\n\n");

    fflush(stdout); 
    while((buffer[i]=getc(stdin))!=EOF)  i++;

    buffer[i]='\0'; 
    bytesstored=sizeof(buffer); 

    if(actualbytes=write(fd,buffer,bytesstored)<0)
    {  
       perror("write");  
       exit(0); 
    } 
    else 
    { 
       write(stdout,"\n\nfile is opened successfully");

       write(stdout,"\nThe contents are written"); fflush(stdout); 
    } 
    if(close(fd)<0) 
    {  
       perror("close");  
       exit(0); 
    } 
    else
       printf("\nfile is closed"); 
 } 
}

解决方案

< has higher precedence than =.

if((fd=open(fn,O_WRONLY|O_CREAT,S_IWUSR|S_IWUSR))<0)

这篇关于C写的()函数不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆