首页 > 解决方案 > 如何逐字读取文件?

问题描述

我很困惑如何在文件中存在的每个单词之后给出换行符。

文本文件中的单词

Name    Date of birth     <----  I put this in code  
John    02\02\1999        <----  I want to jump to this line

我要这个

Here is your: Name
Here is your: Date of Birth

但它给了我这个

Here is your: N 
Here is your: a 
Here is your: m 
Here is your: e 

我不知道如何得到它。

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
    char ch;

    if(fr != NULL){
        while(!feof(fr)){
            ch = fgetc(fr);
            printf("Here is your %c\n: ", ch);
        }
        fclose(fr);
    }
    else{
        printf("Unable to read file.");
    }

    return 0;
}

标签: cfunction

解决方案


在您的while循环中,而不是立即打印您读取的字符,将其存储char在一个char数组中。添加一个if执行比较的语句,以检查读取的内容char是否为空格字符。如果是,您应该打印存储的数组并将数组的索引设置回 0。

例子:

#include <stdio.h>
#include <stdlib.h>

int main(){

    FILE * fr = fopen("file.txt","r");
    char ch[100];
    int index = 0;

    if(fr != NULL){
        while((ch[index] = fgetc(fr)) != EOF){
            //printf("%c\n", ch[index]);
            if(ch[index] == ' ') {
                ch[index] = '\0';
                printf("Here is your: %s\n", ch);
                index = 0;
            }
            else {
                index++;
            }
        }
        fclose(fr);
    }
    else{
        printf("Unable to read file.");
    }
    return 0;
}

推荐阅读