初学者在Linux下的C语言。写功能无法正常工作

时间:2013-05-18 13:26:31

标签: 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;
}

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

我做了一些改动,这应该有效:

#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;

}

答案 1 :(得分:2)

我可以注意到一个错误,写函数的调用:

write (fd,red, sizeof(char));

应该是:

write (fd, &red, sizeof(char));

您在&之前忘了red,写了需要地址。

写法语法:int write( int handle, void *buffer, int nbyte );

这会在运行时的代码中导致undefined behavior

您正在使用未定义的red的写入函数中的

编辑,我认为您的代码中应该是ret变量。将其更正为write (fd, &ret, sizeof(char));

第二,您在; printf("Exiting the program \n")之后忘记了if,但我也认为在发布问题时会出现错误,因为您说您的运行时间错误。

旁注:如果您使用的是gcc编译器,则可以使用gcc -Wall -pedantic生成警告

答案 2 :(得分:2)

应该是:

write (fd,&ret, sizeof(char));

write将指针指向内存位置,由于ret是单个char,因此需要将指针传递给它。