读取系统调用错误(错误的文件描述符)

时间:2012-08-21 05:53:05

标签: c unix

我有这个代码,我在读取系统调用时遇到了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);
}

1 个答案:

答案 0 :(得分:3)

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

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

相关问题