我对在文件处理中使用用户定义的函数的概念并不熟悉。以下是我要执行的操作:
使用fgets()
在没有用户定义功能的情况下存储文件到字符串数组的每一行:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* fptr1;
char words[43][40];
fptr1 = fopen("Skills.txt", "r");
if (fptr1 == NULL)
{
printf("file doesnot exist\n");
exit(1);
}
while (!feof(fptr1))
{
fgets(words[i], 40, fptr1);
i++;
count++;
}
该代码正常运行良好,但是当我尝试使用用户定义的函数来完成这项工作时,出现错误。
使用fgets通过用户定义的功能存储从文件到字符串数组的每一行:
void getSkillsKeywords(char *WORDS[], int* COUNT, FILE* filename);
int main()
{
FILE* fptr1;
char *words[43];
int count = 0;
fptr1 = fopen("Skills.txt", "r");
if (fptr1 == NULL)
{
printf("file doesnot exist\n");
exit(1);
}
getSkillsKeywords(words, &count, fptr1);
for(int i=0;i<count;i++)
printf("%s\n", words[i]);
fclose(fptr1);
}
void getSkillsKeywords(char *WORDS[], int *COUNT, FILE* filename)
{
int i = 0;
char *WORDSS[43];
while (!feof(filename))
{
fgets(WORDS[i], 40, filename); //exception is thrown saying Access violation while reading from file
i++;
*COUNT++;
}
}
我还试图制作另一个用户定义的函数,如下所示:
int main()
{
FILE* fptr1;
int count=0;
fptr1 = fopen("Skills.txt", "r");
if (fptr1 == NULL)
{
printf("file doesnot exist\n");
exit(1);
}
char** words=getSkillsKeywords(&count,fptr1);
for(int i=0;i<count;i++)
printf("%s\n", words[i]);
fclose(fptr1);
}
char** getSkillsKeywords(int* COUNT, FILE* filename)
{
int i = 0, index, u;
char** WORDS =malloc(90*sizeof(char*));
while (!feof(filename))
{
printf("came in");
fgets(WORDS[i], 40, filename); // same exception thrown
i++;
*COUNT++;
}
return WORDS;
}
因为我使用字符串数组,所以我无法使用fgets()
以外的任何其他函数,我需要将每行存储为数组中的元素。错误在哪里,如何解决?
只需填写在您的主函数中声明的单词数组。
#include <stdio.h>
#include <stdlib.h>
void getSkillsKeywords(char [][40], int *, FILE *);
int main() {
FILE* fptr1;
char words[43][40];
int count = 0;
fptr1 = fopen("Skills.txt", "r");
if(fptr1 == NULL) {
printf("file does not exist\n");
exit(1);
}
getSkillsKeywords(words, &count, fptr1);
fclose(fptr1);
for(int i = 0; i < count; i++)
printf("%s", words[i]);
return 0;
}
void getSkillsKeywords(char WORDS[][40], int *COUNT, FILE* filename) {
// no need for the vriable `i` since you have the variable `COUNT`
while(!feof(filename))
fgets(WORDS[(*COUNT)++], 40, filename);
}
示例技能文件
hello Hi there
Wonderful world
Grand master
How is it going
Apples and oranges
输出与我从printf函数中删除换行符的注释相同,因为字符串的末尾已经有换行符。