c - linux下的C初学者。写入功能无法正常工作

标签 c linux

我正在尝试编写一个 C 程序,使用户能够在文件中写入内容。我的问题是,在制作并运行程序后,文件保持为空??知道我该如何解决这个问题。

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


// the user should give a  file to write the file
int main (int argc , char**argv)
{
    int fd; // file descriptor
    char ret; // the character
    int offset;
    if(argc != 2) {
        printf("You have to give the name or the path of the file to work with \n");
        printf("Exiting the program \n")
        return -1;
    }



    fd = open (argv[1], O_WRONLY/*write*/|O_CREAT/*create if not found */, S_IRUSR|S_IWUSR/*user can read and write*/);
    if (fd == -1) {
        printf("can'T open the file ");
        return -1;
    }

    printf("At wich position you want to start ");
    scanf("%d",&offset);
    lseek(fd,offset,SEEK_SET);
    while(1) {
        ret = getchar();
        if(ret == '1') {
            printf("closing the file");
            close (fd);
            return 1;
        }
        else
            write (fd,red, sizeof(char));
    }

    return 0;
}

在此先感谢您的帮助。

最佳答案

我做了一些修改,应该可以:

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

int main (int argc , char**argv) 
{
   int fd; // file descriptor 
   char ret; // the character 
   int offset; 
   if(argc != 2){
     printf("You have to give the name or the path of the file to work with \n");
     printf("Exiting the program \n"); **//There was ';' missing here**
     return -1;
  }
  fd = open (argv[1], O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);
  if (fd == -1) {
     printf("can'T open the file ");
     return -1;
  }

  printf("At wich position you want to start ");
  scanf("%d",&offset);
  lseek(fd,offset,SEEK_SET);
  while(1){
     ret = getchar();
     if(ret == '1'){
     printf("closing the file");
     close (fd);
     return 1;
  }
  else 
     write (fd,&ret, sizeof(char)); **//red has been changed to &ret**
}

  return 0;

关于c - linux下的C初学者。写入功能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16624764/

相关文章:

regex - 从日志文件中提取特定的 XML

linux - Zip 函数垃圾目录路径

c - 按行与按列访问矩阵元素

c - C 中的 udp header 与音频设备通信

c - C中结构的使用

C编程: Do an operation until the desired result

c++ - 堆上的类内的 Linux fork

linux - make 找不到文件

java - 如何使用隐藏终端启动java程序

c - 在使用多个 scanf() 时,它会跳过其余的 scanf()