我正在学习 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;
}
当我在打印/写入时删除 '\n' 字符时,所有数字都会一个接一个地打印出来。我期望。问题是当我包含 \n 字符时,输出包含一些空行。我包括一个输入和输出文件的例子:
输入:
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
如您所见,当原始文件有换行符时,输出包含一个空行,但如果我删除 \n,它会打印/写入一个接一个的数字而没有空格:
4319012305283541322019283407250236041823431541453632261113322309141236184303240813202312210327361709012317222033110118191402301639443203364025410544022006084143210219201733320528113826140803412735352236132117381233133230312645364405180322300236422806112726081307442523112145041827394426382243380510372504360104250602164226284117350617433404412518161910373624201317450344241202013435071104422329080106090526224243142223331215143012373820100331390117334234164401454327114125153130103225420930240137274114261206431112330135024321053027451435420809430807370327140127112337412506030824420320113615214544383436282305210401363805453529341319224405160121111525171338310322033738183632421824451732341905182302233945312133194425134030260524
如果 \n 是显式分隔符,则插入什么字符?