0

I'm trying to write a C program, that make user able to write stuff in a file. My Problem is that after making and running the program the file stay empty ?? any idea how can I solve this.

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

thanks in advance for you help.

4

3 回答 3

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;

}

于 2013-05-18T13:43:36.273 回答
2

它应该是:

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

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

于 2013-05-18T13:44:13.947 回答
2

我注意到一个错误,调用 write 函数:

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

应该:

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

&你之前忘记了red,写下需要的地址。

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

这将导致您的代码在运行时出现未定义的行为

编辑: 在您使用red的未定义的写入函数中,我认为它应该ret在您的代码中是可变的。将其更正为write (fd, &ret, sizeof(char));

;其次,您在 in之后忘记printf("Exiting the program \n")if,但我也认为它在发布问题时犯了错误,因为您说您遇到了运行时错误。

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

于 2013-05-18T13:30:18.373 回答