【问题标题】:read system call error (bad file descriptor)读取系统调用错误(错误的文件描述符)
【发布时间】:2013-02-11 15:12:04
【问题描述】:

我有这段代码,我在读取系统调用时遇到了 BAD FILE DESCRIPTOR 问题。但是,我使用相同文件描述符的写调用工作正常。请推荐

    void Update_Log( )
{
        struct logDetails update,update1[30];
        struct stat fileData,fileData1;
        int file;
        int index;
        //pthread_t pid;
        char writeBuffer[MAX_BUFFER_SIZE];
        char readBuffer[MAX_BUFFER_SIZE];
        char mBuf[MAX_BUFFER_SIZE],mBuf1[MAX_BUFFER_SIZE];
        if((access("/home/team02/DMS/Server/",F_OK))==0) //checking the file/dir existence
                puts("file found");
        else
                puts("file not found");
        if((file=open("/home/team02/DMS/Server/filename.txt",O_RDONLY|O_WRONLY|O_APPEND,S_IRWXU))==-1)
                perror("file not opened");
        if((fstat(file, &fileData))==-1)
                perror("structure not filled");
        if((stat("/home/team02/DMS/Server/f1",&fileData1))==-1)
                perror("structure not filled");

        //printf("%d/n",fileData.st_mtime);
        //printf("%d",fileData.st_ctime);
        struct tm *mytm = localtime(&fileData.st_mtime);
        struct tm *mytime=localtime(&fileData1.st_mtime);
        strftime(mBuf1,18,"%I:%M:%S-%m%d%y",mytime);
        strftime(mBuf, 18, "%I:%M:%S-%m/%d/%y", mytm);
        puts(mBuf);
        if((strcmp(mBuf,mBuf1)==0))
                puts("equal");
                                else
                puts("not equal");
        strcpy(update.timestamp,mBuf);
        strcpy(update.clientName,mBuf);
        strcpy(update.filename,mBuf1);
        snprintf(writeBuffer,MAX_BUFFER_SIZE,"%s %s %s",update.clientName,update.filename,update.timestamp);
        //printf("%s",writeBuffer);
        //if((pthread_create(&pid,&thread_handler,NULL))!=0)
                //perror("Thread not created");
        if((write(file,writeBuffer,strlen(writeBuffer)))==-1)
                perror("write unsuccessful");
        **if((read(file,readBuffer,MAX_BUFFER_SIZE))==-1)
                perror("read unsuccessful");**
        for(index=0;index<strlen(readBuffer);index++)
        {
                sscanf(readBuffer,"%s %s %s",update1[index].clientName,update1[index].filename,update1[index].timestamp);
                printf("%s",update1[index].clientName);
        }
        close(file);
}

【问题讨论】:

  • 你试过用O_RDWR代替O_RDONLY|O_WRONLY吗?

标签: c unix


【解决方案1】:

根据运行时库,打开模式O_RDONLY|O_WRONLY 可能会出现问题。您可能希望 O_RDWR 替换该部分。

此外,您可以获取errno 值以找出问题所在。 如果出现错误,您正在调用perror()。那应该告诉你问题是什么。程序产生什么输出?

【讨论】:

  • @aviral - 那么问题出在哪里?你是如何“让它工作”的?
  • 但是我在 readBuffer 中没有得到任何东西..有什么建议吗?
  • @paulsm4 我按照 wallyk 指定的方式更改了标志。
  • @aviral:打开模式是追加,所以写入追加在文件末尾。你希望它在那个时候读到什么?它位于文件末尾。
  • 它正在设置 EBADF :bad file descriptor
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2011-09-08
相关资源
最近更新 更多