LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 986|回复: 6

关于创建一个文件并向文件里写入数据的问题,请各位大虾帮忙解决一下

[复制链接]
发表于 2004-3-8 13:26:28 | 显示全部楼层 |阅读模式
我用C写了一个程序,可就是不能向文件“test.dat”中写入字符。代码如下:
[php]
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

#define NEWFILE (O_WRONLY|O_CREAT|O_TRUNC)



int main(void)
{
            int outfile,n;
            char filename[ ]={"test.dat"};
        char file[]={"hello,how are you"};

        if(outfile=open(filename, NEWFILE, 0640)==-1)
        {
                    printf("ERROR, OPEN FILE FAILED! \n");
                    exit(255);
        }
          if(n=write(outfile,file,sizeof(file))==-1)
            {printf("writed file error\n");
              exit(255);
             }
                    close(outfile);
            return 0;
}
[/php]
:help
发表于 2004-3-8 16:30:04 | 显示全部楼层
这是小弟用c写的,

  1. #include <stdio.h>

  2. int main(void)
  3. {
  4.         FILE *fp;
  5.         char *s = "Hello World!";
  6.         fp = fopen("test.data","rw");
  7.         if (fp==NULL)
  8.                 printf("open error\n");
  9.         fprintf(fp, "%d", s);
  10.         fclose(fp);
  11. }
复制代码

你写的,我很多地方不懂啊,
发表于 2004-3-8 16:46:41 | 显示全部楼层
错在这里:

  1. if ([color=red]([/color]outfile = open(filename, NEWFILE, 0640)[color=red])[/color] == -1)
  2. {
  3.     printf("ERROR, OPEN FILE FAILED! \n");
  4.     exit(255);
  5. }
  6. if ((n = write(outfile,file,sizeof(file))) == -1)
复制代码
发表于 2004-3-8 16:47:38 | 显示全部楼层
错在这里:

  1. if ([color=red]([/color]outfile = open(filename, NEWFILE, 0640)[color=red])[/color] == -1)
  2. {
  3.     printf("ERROR, OPEN FILE FAILED! \n");
  4.     exit(255);
  5. }
  6. if ((n = write(outfile, file, sizeof(file))) == -1)
复制代码


对,应该保持良好的编程风格的
原来不会粘贴代码的:p
发表于 2004-3-8 16:50:10 | 显示全部楼层
n=……的错误也是一样

发错的贴子怎么删掉?:confused:
发表于 2004-3-8 20:39:15 | 显示全部楼层
发错的贴子自己删不掉,只有版主有这个权限。
顺便说一下:楼主下次发贴请注意保持缩进。
 楼主| 发表于 2004-3-9 18:36:26 | 显示全部楼层
谢谢各位大虾
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表