我正在从事C编程中的作业,并且有一些理解上的困难。我创建了一个应该创建文件夹或文件的函数(仅包含字符串)。如果新对象是一个文件夹,我想递归输入子文件的数量。
[问题:如果要使用第二个文件(仅字符串)的数据,如何访问子文件? (以及访问子文件夹)。
文件结构:
typedef struct {
char *name; //name of File
char type; // 'f' - data file, 'd'-folder.
union {
char data[5]; //f -80 chars array for content of file.
struct { //d -arry of pointers to 'File' Files.
struct File ** files;
unsigned int size;
}folder;
}content;
}File;
功能:
File * newFile(char type)
{
File *pfile = (File*)malloc(sizeof(File)); //creating new File
if (!pfile) {
printf("No memory for new file\n");
exit(1);
}
if (type != 'f' || type != 'd') { // in case of wrong input of type.
while(type != 'f' && type !='d'){
printf("Wrong input,try again: ");
fseek(stdin, 0, SEEK_END);
type =getchar();
}
}
printf("Enter File name: ");
fseek(stdin, 0, SEEK_END);
char name[NAME];
gets(name);
pfile->name = name;
if (type == 'f') { // New File is 'folder'
pfile->type = 'f';
//fseek(stdin, 0, SEEK_END);
printf("Enter number of files in %s: ",pfile->name);
scanf(" %d", &pfile->content.folder.size);
if (pfile->content.folder.size == 0) { // Zero files in the folder
pfile->content.folder.files = NULL; // No more files / empty folder
}
pfile->content.folder.files = (File**)malloc(pfile->content.folder.size * sizeof(File));
if (!pfile->content.folder.files) {
printf("No memory for sub files\n");
exit(2);
}
for (int i = 0; i < pfile->content.folder.size; ++i) { // creates 'size' file per folder
fseek(stdin, 0, SEEK_END);
printf("(%d):Enter type of file (d-folder,f-file): ", i + 1);
pfile->content.folder.files[i] = newFile(getchar());
}
return pfile;
}
else if (type == 'd') { //File creation
pfile->type = 'd';
printf("Enter file's text:\n");
scanf(" %s", &pfile->content.data);
}
return pfile;
我相信这是问题所在:
if (type != 'f' || type != 'd') { // in case of wrong input of type.
while(type != 'f' && type !='d'){
printf("Wrong input,try again: ");
fseek(stdin, 0, SEEK_END);
type =getchar();
}
}
您应更改“ ||”就像在while循环中一样,在if到“ &&”中,您的问题应该得到解决,或者只是删除if并离开while循环。