【问题标题】:how to get string from a struct in C? [closed]如何从C中的结构中获取字符串? [关闭]
【发布时间】:2016-12-09 12:58:52
【问题描述】:

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

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

FILE* outfile = fopen("Z:\\NH\\instructions.txt","wb");
if ((dir = opendir ("Z:\\NH\\sqltesting\\")) != NULL) {// open directory and if it exists

         while ((ent = readdir (dir)) != NULL) { //while the directory isn't null
                 printf("%s\n", ent->d_name);  //I can do THIS okay

                 fprintf("%s\n",ent->d_name); //but I can't do this

                    fclose(outfile);

                                        }

                    }   
                        closedir (dir);

                //else { 
                 //
                    //           perror (""); //print error and panic
                        //     return EXIT_FAILURE; 
                    //}
            }

我在这里采取了错误的方法吗?我正在考虑以某种方式使用char[80] =ent.d_name; 但是显然这不起作用。有什么方法可以从结构中获取该字符串并将其放入 fprintf 中?

【问题讨论】:

  • 嘿?你读过手册页吗?
  • 另外,没有关于结构的信息。
  • fprintf() 不采用格式字符串作为第一个参数。
  • fprintf(outfile,"%s", ent->d_name)。你必须给 fprintf 指向文件的指针作为第一个参数

标签: c string struct char


【解决方案1】:

来自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;
}

【讨论】:

    【解决方案2】:

    假设

    char dname[some_number];
    

    和结构对象

    ent //is not a pointer
    

    fprintf(outfile,"%s\n",ent.d_name); // you missed the FILE* at the beginning
    

    如果ent 是一个指针,那么上面的语句会变成

    fprintf(outfile,"%s\n",ent->d_name); // note the ->
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多