错误:使用需要标量的结构类型值

时间:2015-12-02 23:02:13

标签: c

我正在创建一个程序,它接受输入并打开文本文件,并根据用户的需要将单词更改为大写或大写。当我编译程序时,我收到以下错误:

22:11: error: used struct type value where scalar is required
30:11: error: used struct type value where scalar is required

  1 #include <stdio.h>
  2 int main(void) {
  3
  4         char choice;
  5         char fileName;
  6         char newFileName;
  7         int i = 0;
  8
  9         printf("Change Case \n");
 10         printf("============\n");
 11         printf("Case (U for upper, L for lower) : ");
 12         scanf(" %c", &choice);
 13         printf("Name of the original file : oldFile.txt \n");
 14         printf("Name of the updated file : newFile.txt \n");
 15
 16         FILE *fp = NULL;
 17
 18         fp = fopen("oldFile.txt", "a");
 19
 20         if (fp != NULL && choice == 'L') {
 21
 22                 while ( fp[i] ) {
 23
 24                         putchar(tolower(fp[i]));
 25                         i++;
 26                 }
 27         }
 28         else if (fp != NULL && choice == 'U') {
 29
 30                 while ( fp[i] ) {
 31
 32                         putchar(toupper(fp[i]));
 33                         i++;
 34                 }
 35         }
 36         else {
 37
 38                 printf("ERROR: No proper choice was made \n");
 39         }
 40 }

4 个答案:

答案 0 :(得分:3)

fp文件指针,而不是文件中的数组。 Have a look at use of fopen in a tutorial.

您需要使用类似fgets的内容将文件读入缓冲区。您也可以使用fgetc一次读取一个字符的文件。

答案 1 :(得分:1)

访问文件指针fp的错误方法。它是指向文件的指针,而不是数组字符或字符串。每次打开文件时,系统都会将文件指针放在文件的开头,该文件指针偏移为零。

使用fclose(fP);

处理后,每次关闭打开的文件

示例使用文件指针的示例代码段。

int c;
fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);// or fgets as per the usage
      if( c==EOF)
      { 
        //Exit
      }
      // your code 
   }
   fclose(fp);

答案 2 :(得分:0)

文件指针不是数组...考虑使用fgetc / fgets。 fp[i]没有给你文件的第i个字节。 fgetc会让你迭代文件的字节,并在你结束时返回EOF。

请参阅fgetc here的文档。

答案 3 :(得分:0)

以下是如何从txt获取字符串的示例。还有很多其他方法

#include <stdio.h>

int main(void) {

    FILE *fp;
    fp = fopen("oldFile.txt", "r");
    char str[1024];
    while(fgets(str, 1024, fp)!=NULL) {     //acquire strings from oldFile.txt through fgets() which returns a pointer. NULL is returned at the end of file
        printf("%s", str); //just an example
    }
}