这是有问题的代码:
FILE *fp;
char str[256];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
char *temp;
temp=malloc(257);
for(i=0;i<sizeof(str)-1;i++){
if(isalpha(str[i])){
append(temp,str[i]);
}else{
printf(" %s ",temp);
temp=calloc(257,sizeof(char));
}
}
}
如果文本文件如下:
"Here's a text
file example. No
idea what's wrong."
然后输出以下内容:
"Here s a text vf file example No vf idea what s wrong".
所需输出供参考:
"Here s a text file example No idea what s wrong"
每次涉及新行时,基本上都是一些奇怪的东西。当我运行它时可能是“vf”。下次可能是“ZG”。每次运行程序时它都会改变。
答案 0 :(得分:0)
读取buf
未被fgets()`填充的部分。
替换
// for(i=0;i<sizeof(str)-1;i++)
for(i=0;i<strlen(str);i++)
或更好
// for(i=0;i<sizeof(str)-1;i++)
size_t len = strlen(str);
// removed potenital ending '\n'
if ((len > 0) && (str[len-1] == '\n')) len--;
size_t i;
for (i = 0; i < len; i++)
答案 1 :(得分:0)
也许我不明白你在做什么,但如果你只是想用一个字符串读取整个文件,你可以做这样的事情
int main(int argc, const char * argv[])
{
FILE *fp;
char str[256];
char *temp = calloc(257, 1);
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
//char *temp;
if (str[strlen(str)-1] == '\n') {
str[strlen(str)-1] = ' ';
}
strncat(temp, str, 257);
}
puts(temp);
}
fgets
没有问题。它会自动附加终止空字符。
此外,在分配新内存之前,您不会释放内存。这不好。
答案 2 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char str[256];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
char temp[256]; //buffer; can allocate on the stack, no need for malloc
char *temp1; //pointer at the beginning of the buffer (used to do my own append())
temp1=temp; //for my own appending
for(i=0;i<sizeof(str);i++){
int ch=str[i]; //alias the str[i]
if(isalpha(ch)||ch=='"'){ //let these chars thru
*temp1++=ch; //my own append()
}else if(ch=='\0'){//already at the end of buffer, end loop and print
*temp1=ch; //don't forget to end the string with '\0' (for printing functions)
break;
}else if(ch=='.'){ // you seem to want to skip dots
continue;
}
else {
*temp1++=' '; //replace other nonalpha characters with ' '
}
}
printf("%s",temp);
}
}