Zelea
沉默的牧羊者
采纳率75%
2017-04-11 15:44 阅读 2.3k

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 oyljerry 2017-04-12 01:15

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

    点赞 评论 复制链接分享
  • sun1021873926 夕阳雨晴 2017-04-12 04:54

    还有一个需要注意的地方是linux服务器的连接工具上的编码设置,也需要设置成utf-8

    点赞 评论 复制链接分享

相关推荐