无法在C中打开文件描述符

时间:2013-11-22 14:31:47

标签: c file-descriptor

这是我尝试打开文件描述符并向其写入数据的代码。

#include <stdio.h>
#include <stdlib.h> 
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void usage(char *prog_name,char *filename)
{
    printf("Usage: %s <data to add to %s>\n", prog_name, filename);
    exit(0);

}
void fatal(char *);
void *ec_malloc(unsigned int);

int main(int argc,char *argv[])
{
    int fd;
    char *buffer,*datafile;
    buffer =   (char*)ec_malloc(100);
    datafile = (char*)ec_malloc(20);
    strcpy(datafile,"/home/note");
    if(argc<2)
        usage(argv[0],datafile);

    strcpy(buffer,argv[1]);
    printf("[DEBUG] buffer@ %p: \'%s\'\n", buffer, buffer);
    printf("[DEBUG] datafile @ %p: \'%s\'\n", datafile, datafile);
    strncat(buffer,"\n",1);
    fd = open(datafile,O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR);
    if(fd = -1)
        fatal("In main() while opening file\n");
    printf("[DEBUG] file descriptor is %d\n", fd);
    if(write(fd, buffer, strlen(buffer)) == -1)
        fatal("in main() while writing buffer to file");
    if(close(fd) == -1)
       fatal("in main() while closing file");
    printf("Note has been saved.\n");
    free(buffer);
    free(datafile);
}

void fatal(char *message){
    char error_message[100];
    strcpy(error_message,"[!!] Fatal Error ");
    strncat(error_message,message,strlen(message));
    perror(error_message);
    exit(-1);
}

void *ec_malloc(unsigned int x){
    void *ptr = malloc(x);
    if(ptr == NULL)
        fatal("in ec_malloc() on memory allocation");
    return ptr;

}

现在如果我不给任何CL参数,那么响应是 Usage: ./simplenote <data to add to /tmp/note> 但是如果我给出命令行,例如,./simplenote "This is a test",则不返回filedescriptor。这是我得到的输出,

[DEBUG] buffer@ 0x1edf010: 'this is a test note'
[DEBUG] datafile @ 0x1edf080: '/tmp/note'
[!!] Fatal Error In main() while opening file
: Success

那么,问题是什么?为什么不能打开文件?

3 个答案:

答案 0 :(得分:4)

if(fd = -1)

这是一个赋值,并且总是产生一个不等于零的值,因此总是输入if的正文。

答案 1 :(得分:3)

if(fd = -1)应为if(fd == -1)

答案 2 :(得分:1)

if(fd = -1)应为if(fd == -1),如果您想避免此类错误,可以随时执行“YODA技巧”: 写:if(-1 == fd)而不是if(fd == -1)。它是一样的,但是如果你犯了错误if(-1 = fd),它将抛出一个编译错误!