沉默的牧羊者 2017-04-11 15:44 采纳率: 75%
浏览 2406
已采纳

Linux下关于读文件出现乱码的问题

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include<pthread.h> 
#include <semaphore.h>

#define infile "infile.dat"
#define outfile "outfile.dat"

sem_t f1;
sem_t f2;

void inputdata()
{
    int infd;
    char buf[50];

    if ((infd = open(infile, O_WRONLY | O_TRUNC | O_CREAT, 10700)) == -1)
    {
        printf("ERROR, OPEN READ FILE FAILED:%s \n", sys_errlist[errno]);
        exit(255);
    }

    printf("Please enter the data:\n");
    printf("(Ctrl+D ---- quit)\n");

    while(fgets(buf, sizeof(buf), stdin))
    {
        if (write(infd, buf, strlen(buf)) != strlen(buf))
        {
            printf("ERROR, WRITE FILE FAILED:%s \n", sys_errlist[errno]);
            exit(255);
        }
    }
    close(infd);

    sem_post(&f1);
}

void copydata()
{
    sem_wait(&f1);

    int infd, outfd;
    char buf[50];

    if ((infd = open(infile, O_RDONLY))==-1)
    {
        printf("ERROR, OPEN READ FILE FAILED:%s \n", sys_errlist[errno]);
        exit(255);
    }

    if ((outfd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 10700))==-1)
    {
        printf("ERROR, OPEN WRITE FILE FAILED:%s \n", sys_errlist[errno]);
        exit(255);
    }

    int count;

    while((count = read(infd, buf, sizeof(buf))) > 0)
    {
        if (count != write(outfd, buf, strlen(buf)))
        {
            printf("ERROR, WRITE FILE FAILED:%s \n", sys_errlist[errno]);
            exit(255);
        }
    }

    close(infd);
    close(outfd);

    sem_post(&f2);
}


void showdata()
{
    sem_wait(&f2);

    int outfd;
    char buf[50];

    if ((outfd = open(outfile, O_RDONLY, 10700))==-1)
    {
        printf("ERROR, OPEN WRITE FILE FAILED:%s \n", sys_errlist[errno]);
        exit(255);
    }

    int count;

    printf("\nThe data in the file:\n");

    while((count = read(outfd, buf, sizeof(buf))) > 0)
    {
        printf("%s", buf);
    }

        close(outfd);
}

void main()
{
    pthread_t t1,t2,t3,t4;
    sem_init(&f1,0,0);
    sem_init(&f2,0,0);

    pthread_create(&t1,NULL, (void *)showdata, NULL);
    pthread_create(&t2,NULL, (void *)copydata, NULL);
    pthread_create(&t3,NULL, (void *)inputdata, NULL);

    pthread_join(t1,NULL);
}

图片说明

我想问一下,我觉得这段程序已经没有问题了,但是最后一步读文件时,会出现上面标记的乱码,这是为什么??难道是缓冲区的问题吗??

  • 写回答

2条回答 默认 最新

  • oyljerry 2017-04-12 01:15
    关注

    文件编码。和你读取数据保存的编码还有输出的编码。这几个地方

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题