Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to read the file in my PC,should I change my code?The file is C:\123.txt

0 votes
asked Aug 25, 2023 by 洪麒麟 (160 points)
reshown Aug 27, 2023 by 洪麒麟
void main(void)
{
    FILE *fp;
    fp = fopen("C:\\123.txt","r");
    if(!fp){
        printf("檔案開啟失敗!!");
        return;
    }
    
    int count = 0;
    char c;
    while((c = getc(fp)) != EOF){
        if(c == 'A')
            count ++ ;
    }
    
    printf("A的數量為%d",count);
    fclose(fp);
}

1 Answer

+2 votes
answered Aug 27, 2023 by Peter Minarik (87,810 points)
selected Oct 3, 2023 by 洪麒麟
 
Best answer

I guess you run into the problem of not being able to open the file.

This is because you need to escape special characters in strings, such as backslash. So your path correctly escaped would be:

FILE * fp = fopen("C:\\123.txt", "r");
commented Aug 27, 2023 by 洪麒麟 (160 points)
Thank you for your answer. But after I modified the code to fopen("C:\\123.txt", "r"), reading the file still failed.
commented Sep 13, 2023 by Алексей Анцибор (110 points)
thank you! It was very helpful for me!
commented Sep 13, 2023 by Peter Minarik (87,810 points)
Can you share your code (there is an orange SHARE) button on the code editor page if you still have an issue?
commented Sep 22, 2023 by 洪麒麟 (160 points)
The following code is my code still run to printf("檔案開啟失敗!!"):
(Maybe it's because the program is executed in the browser?)


#include <stdio.h>

void main(void)
{
    FILE *fp;
    fp = fopen("C:\\123.txt","r");
    if(!fp){
        printf("檔案開啟失敗!!");
        return;
    }
    
    int count = 0;
    char c;
    while((c = getc(fp)) != EOF){
        if(c == 'A')
            count ++ ;
    }
    
    printf("A的數量為%d",count);
    fclose(fp);
}
commented Sep 22, 2023 by Peter Minarik (87,810 points)
That's right.

That code will run on the server, not on your local machine. There's no file on the path C:\123.txt on the server.

You can add files to your project (any file, even the 123.txt) with the NEW FILE or UPLOAD FILE button just left to the green RUN button. Those files will be available when you run your code.

In that case, you relative paths, not absolute paths, that is, fopen("123.txt", "r").

Good luck!
commented Oct 3, 2023 by 洪麒麟 (160 points)
Thank you, this problem is perfectly solved.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...