如何在C中从结构中获取字符串?

如何在C中从结构中获取字符串?,c,string,struct,char,C,String,Struct,Char,我很好奇以前是否有人这样做过 我在从结构获取字符串时遇到问题。我要做的是从我正在使用的特定结构中获取字符串,然后将该字符串放入fprintf(“%s”,whateverstring) 我是不是走错了路?我在考虑以某种方式使用类似于char[80]=ent.d_name 然而,这显然不起作用。有什么方法可以从结构中获取该字符串并将其扔到fprintf中吗 假设 char dname[some_number]; 以及结构对象 ent //is not a pointer 做 如果ent是指针,则

我很好奇以前是否有人这样做过

我在从结构获取字符串时遇到问题。我要做的是从我正在使用的特定结构中获取字符串,然后将该字符串放入fprintf(“%s”,whateverstring)

我是不是走错了路?我在考虑以某种方式使用类似于
char[80]=ent.d_name
然而,这显然不起作用。有什么方法可以从结构中获取该字符串并将其扔到fprintf中吗

假设

char dname[some_number];
以及结构对象

ent //is not a pointer

如果
ent
是指针,则上述语句将更改为

fprintf(outfile,"%s\n",ent->d_name); // note the ->
从的手册页中,函数声明为:

int fprintf(FILE *stream, const char *format, ...);
你没有包括第一个论点。下面是一个简单的程序,证明您可以将目录的内容写入文件:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
    FILE *outfile;
    DIR *dir;
    struct dirent *ent;        

    outfile = fopen("Z:\\NH\\instructions.txt","wb");
    if (outfile == NULL)
    {
        return -1;
    }

    dir = opendir ("Z:\\NH\\sqltesting\\");
    if (dir == NULL)
    {
        fclose (outfile);
        return -1;
    }

    while ((ent = readdir (dir)) != NULL)
    {
        fprintf (outfile, "%s\n", ent->d_name);
    }

    fclose (outfile);
    closedir (dir);
    return 0;
}
#包括
#包括
#包括
内部主(空)
{
文件*输出文件;
DIR*DIR;
结构导向;
outfile=fopen(“Z:\\NH\\instructions.txt”、“wb”);
if(outfile==NULL)
{
返回-1;
}
dir=opendir(“Z:\\NH\\sqltesting\\”;
if(dir==NULL)
{
fclose(输出文件);
返回-1;
}
while((ent=readdir(dir))!=NULL)
{
fprintf(输出文件,“%s\n”,ent->d_名称);
}
fclose(输出文件);
closedir(dir);
返回0;
}

heh?你读过手册吗?而且,没有关于结构的信息。不将格式字符串作为第一个参数。fprintf(输出文件,“%s”,ent->d_名称)。必须将指向文件的指针作为第一个参数提供给fprintf
int fprintf(FILE *stream, const char *format, ...);
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
    FILE *outfile;
    DIR *dir;
    struct dirent *ent;        

    outfile = fopen("Z:\\NH\\instructions.txt","wb");
    if (outfile == NULL)
    {
        return -1;
    }

    dir = opendir ("Z:\\NH\\sqltesting\\");
    if (dir == NULL)
    {
        fclose (outfile);
        return -1;
    }

    while ((ent = readdir (dir)) != NULL)
    {
        fprintf (outfile, "%s\n", ent->d_name);
    }

    fclose (outfile);
    closedir (dir);
    return 0;
}