#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *userfile, *pwfile, *usernamesPasswords, *readUsernamesPasswords;
char u, p, user[20][25], pass[20][20], userLine[25], passLine[20];
int i = 0;
int j = 0;
int userIndex = 0;
int passIndex = 0;
userfile = fopen("usernames.txt", "r");
pwfile = fopen("passwords.txt", "r");
if (userfile == NULL || pwfile == NULL) {
printf("Cannot open file \n");
exit(0);
}
u = fgetc(userfile);
while (u != EOF) {
if ( u != '\n'){
userLine[userIndex++] = u;
} else {
userLine[userIndex] = '\0';
strcpy(user[i], userLine);
userIndex = 0;
i++;
}
u = fgetc(userfile);
}
fclose(userfile);
p = fgetc(pwfile);
while (p != EOF) {
if ( p != '\n'){
passLine[passIndex++] = p;
} else {
passLine[passIndex] = '\0';
strcpy(pass[j], passLine);
passIndex = 0;
j++;
}
p = fgetc(pwfile);
}
fclose(pwfile);
usernamesPasswords = fopen("usernamesPasswords.txt", "w");
int w, k;
char newLine[1024];
for (w=0;w<20;w++) {
strcat(newLine, user[w]);
int q = strlen(newLine);
for (k=0;k<(25-q);k++) {
strcat(newLine, " ");
}
strcat(newLine, pass[w]);
strcat(newLine, "\n");
strcat(newLine, "\0");
fputs(newLine ,usernamesPasswords);
strcpy(newLine, "");
}
fclose(usernamesPasswords);
printf("\nDo you want to display the new file? Enter (y) to view and any other key to exit\n");
char word;
scanf("%c",&word);
if (word == 'y') {
readUsernamesPasswords = fopen("usernamesPasswords.txt", "r");
if (readUsernamesPasswords == NULL) {
printf("Cannot open file \n");
exit(0);
}
char r;
while((r=fgetc(readUsernamesPasswords))!=EOF) {
printf("%c", r);
}
fclose(readUsernamesPasswords);
}
return 0;
}
预期输出:
Moodie 123456
Intelllligent password
Happee 12345678
Mischeivous qwerty
SweetKristy 123456789
KristyHoney 12345
BubblySnowflake 1234
AngelicPrincessKristy 111111
FairyPrincessKristy 1234567
BabyKristyButterfly dragon
daffyusers 123123
magpiedoodle baseball
aspiringthreat abc123
landmarksspreader football
cavaliervanquish monkey
chatteringparma letmein
veggiehydrogen 696969
teethunsure shadow
rumpboast master
lidarstrudel 666666
相反...
123456
password
12345678
qwerty
123456789
12345
1234ke
111111incessKristy
1234567sKristy
dragonutterfly
123123
baseball
abc123
footballer
monkeysh
letmein
696969
shadow
master
666666
只有当我尝试在终端上输出时才会发生这种情况。 实际的 usernamesPasswords.txt 文件按预期出现。 字符串的左侧似乎只有在我用换行符代替空格时才会打印...
我什至尝试了 fgets 和 fread,但输出结果相似。我读过其他关于饮食或消费的帖子,所以我尝试按照建议使用 fgets 或 fread,甚至尝试使用 unget。似乎没有用。我一直在寻找堆栈溢出无济于事。
如果这是重复的,我提前道歉。在决定发布之前,我真的尝试在网上浏览了几个小时。
我通常不发布因为堆栈溢出通常已经包含了所有内容...
求助!谢谢!
最佳答案
您不能在未初始化的存储上调用 strcat
或 strlen
。这是未定义的行为。字符串函数通常要求输入字符串参数以正确的 NUL 结尾。 (没有终止符,就无法判断字符串在哪里结束。)
strcat(s, "\0")
是空操作,因为第二个参数实际上是一个空(零长度)字符串。 (并且,如上所述,如果 s
尚未以 NUL 终止,则它是未定义的行为。)
关于c - fgetc 在空格后无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717430/