void word(FILE*fptr, char sender[]);
void dosya(){
FILE *fp1;
fp1 = fopen("com.txt","r");
int c, i, sendno=0, receiveno=0;
char d, e, send, space1, space2, receive;
char* sender = malloc(sizeof(char));
while(send != ' '){ /*read sender's name*/
send = getc(fp1);
if(send == ' ')
break;
else{
sender[sendno] = send;
sendno++;
sender = (char *) realloc(sender, (sendno+1)*sizeof(char));
}
}
e = getc(fp1); /* read # character */
word(fp1, sender);
fclose(fp1);
}
void word(FILE*fptr, char sender[]){
printf("%s", sender);
}
// Driver program to test above functions./
int main()
{
dosya();
return 0;
}
我使用malloc创建一个称为sender的动态数组,并在每次读取字母时重新分配它,当字母为空格字符时它将停止。我想在另一个函数中使用此数组。如何在文字功能中实现它?
答案 0 :(得分:0)
getc()
没有明确指示EOF(=end of file)
状态,如果文件中不存在空格字符,则会无限期循环。这就是为什么您的打印函数永远不会被调用的原因。
还有其他一些问题使您的代码难以阅读,这就是为什么调试起来可能如此困难的原因。
因此,我建议您按以下方式重做程序:
realloc()
对于每个字符都是多余的,请在循环中计数字符,然后使用malloc动态创建一个数组并使用strncpy
/ memcpy
或类似的内容保存输入代码:
int Exists(const char *path)
{
if (fopen(path, "r") == NULL)
{
return -1;
}
fclose();
return 1;
}
void ReadLine(const char *path)
{
if (Exists(path) == -1)
{
printf("file doesnt exist \n");
}
else
{
char buffer[256];
FILE *fp = fopen(path, "r");
char *key = (char*)malloc(sizeof(char));
int n = 0;
while (fgets(buffer, 255, fp) != NULL) // read file till newline/255 c limit
{
for (int i = 0; i < sizeof(buffer) / sizeof(char); i++)
{
if (buffer[i] == ' ' || buffer[i] == '\n')
{
if (i > (strlen(key)))
{
(char*)realloc(key, i * sizeof(char));
}
strncpy(key, buffer, i);
key[i] = '\0';
break;
}
}
//key now holds value of words separated by whitespace or newline character
}
}
fclose();
free(key);
}
答案 1 :(得分:0)
将void dosya()
原型更改为char *dosya()
。将分配的sender
返回到main()
,将其存储在变量中,发送到word()
并释放所有分配的内存。
赞:
char *dosya() {
// ...
// collect data
// ...
return sender;
}
//...
int main()
{
FILE *fptr;
char *p;
// ...
// open file for fptr
//
if (fptr == NULL)
return -1;
p = dosya();
if (p != NULL) {
word(fptr, p);
free(p);
}
return 0;
}
malloc()
的{{1}}和realloc()
返回值(内存不足); NULL
的末尾添加'\0'
分隔符; sender
对于每个字符来说都是非常低效的方式,但这超出了原始问题。