使用strsep()读取文本文件时清空行/字符

时间:2018-05-05 02:18:34

标签: c string strsep

我正在学习C并且作为练习,我尝试在每行中读取具有不同数字集的文件,并且每行打印(或保存到不同的文件)每个数字(也作为字符串)。

您可以在此处查看代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 40

int main(){

    char numbers[SIZE];
    FILE *fileRead;
    FILE *fileWrite;
    char *token, *tofree, *str;

    fileRead = fopen("/Users/USER/Documents/readfile.txt", "r");
    if (fileRead==NULL){
        printf("File not found\n");
        return 1;
    }

    fileWrite = fopen("/Users/USER/Documents/writefile.txt", "w");
    if (fileWrite==NULL){
        printf("File not found\n");
        return 1;
    }

    while (!feof(fileRead)){
        fgets(numbers, SIZE, fileRead);
        tofree = str = strdup(numbers);
        while ((token = strsep(&str, " \n"))) fprintf(fileWrite,"%s\n", token);
        free(tofree);

    }
    puts("Succeed");
    return 0;
}

当我删除&#39; \ n&#39;在打印/书写时,所有数字都是一个接一个地打印出来的。我期望。 问题是当我包含\ n char时,输出包含一些空行。我提供了输入和输出文件的示例:

输入:

43 19 01 23 05 28 35
41 32 20 19 28 34 07
25 02 36 04 18 23 43
15 41 45 36 32 26 11
13 32 23 09 14 12 36
18 43 03 24 08 13 20
23 12 21 03 27 36 17
09 01 23 17 22 20 33
11 01 18 19 14 02
30 16 39 44 32 03
36 40 25 41 05 44
02 20 06 08 41 43
13
15

输出:

43
19
01
23
05
28
35

41
32
20
19
28
34
07

25
02
36
04
18
23
43

15
41
45
36
32
26
11

13
32
23
09
14
12
36

18
43
03
24
08
13
20

23
12
21
03
27
36
17

09
01
23
17
22
20
33

11
01
18
19
14
02

正如您所看到的,当原始文件有换行符时,输出包含一个empt行,但是如果我删除了\ n,它只打印/写入一个不带空格的数字:

4319012305283541322019283407250236041823431541453632261113322309141236184303240813202312210327361709012317222033110118191402301639443203364025410544022006084143210219201733320528113826140803412735352236132117381233133230312645364405180322300236422806112726081307442523112145041827394426382243380510372504360104250602164226284117350617433404412518161910373624201317450344241202013435071104422329080106090526224243142223331215143012373820100331390117334234164401454327114125153130103225420930240137274114261206431112330135024321053027451435420809430807370327140127112337412506030824420320113615214544383436282305210401363805453529341319224405160121111525171338310322033738183632421824451732341905182302233945312133194425134030260524

如果\ n是显式分隔符,则插入什么字符?

0 个答案:

没有答案