C:警告:格式'%s'需要匹配的'char *'参数

时间:2013-10-11 11:30:30

标签: c pointers file-io printf

我目前正在处理文件I / O,我尝试使用此功能:

fprintf (FILE *pFile, char *pFormat, <variable list>);

使用我的变量

fprintf ( filePtr, "\"%s\"n", myarray );

我的编译器发出警告warning: format '%s' expects a matching 'char *' argument,但我已将myarray声明为char *myarray = "This is a string"。谁能告诉我出了什么问题?我的代码是:

#include <stdio.h>
int main ()
{
FILE *filePtr;
char *myarray = "This is a string";

if ((filePtr = fopen("sample.dat", "w")) == NULL) {
   printf ("File could not be opened.\n");
} else {
   printf ("This will print the string onto file:\n");

   while (!feof(filePtr)) {
      fprintf ( filePtr, "\"%s\"", myarray );
   }
}
fclose (filePtr);
return 0;
}

1 个答案:

答案 0 :(得分:1)

我尝试用gcc编译,它发现了另一个问题 - 在fopen中缺少参数:

 if ((filePtr = fopen("sample.dat")) == NULL) {

所以,需要使用:

 if ((filePtr = fopen("sample.dat", "r")) == NULL) {

此后,代码编译没有问题。 编译器版本:

gcc version 4.2.1 20070831 patched [FreeBSD]