C语言请问如何 读取一个文件中的字符?

用c打开一个TXT文件并读取里面的字符 在读写指定文件时出现错误 请问该如何解决?

clipboard.png

include<stdio.h>

include<stdlib.h>

int main(void)
{

FILE *fp;
char str[3][10];
int i = 0;
if ((fp = fopen_s("C:\Users\ASUS\Desktop.txt", "r",10)) == NULL)
{
    printf("can't open file!\n");
    exit(0);
}
while (fgets(str[i], 10, fp) != NULL)
{
    printf("%s", str[i]);
    i++;
}
fclose(fp);
return 0;

}

阅读 6.7k
1 个回答

函数用错了,你把 fopen_s 当成 fopen 在用了,它们的参数并不相同。

fopen_s 示例(仅供参考)

// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-s-wfopen-s
// errno_t fopen_s(FILE** pFile, const char *filename, const char *mode);

#include <stdio.h>

int main( void )
{
   FILE *stream;
   errno_t err;
   // Open for read (will fail if file "crt_fopen_s.c" does not exist)
   err  = fopen_s( &stream, "crt_fopen_s.c", "r" );
   if( err == 0 )
      printf( "The file 'crt_fopen_s.c' was opened\n" );
   else
      printf( "The file 'crt_fopen_s.c' was not opened\n" );
}

fopen 示例(仅供参考)

// http://www.cplusplus.com/reference/cstdio/fopen/
// FILE * fopen ( const char * filename, const char * mode );

#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ("myfile.txt","w");
  if (pFile!=NULL)
  {
    fputs ("fopen example",pFile);
    fclose (pFile);
  }
  return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进