0

I am new to command line, i have a problem. i have searched to solve the problem but none of them work . I want to use command line to open file but i cant open it and i don't know why. I checked if i created my file yet.I did change the working directory, but it still cant find my file.

My code

#include<iostream>
#include<string>
using namespace std;
void main(int i ,char *a[])
{
    if (i != 1)
    {
        cout << "Wrong!!!";
    }
    fstream fp;
    fp.open(a[1]);
    if (!fp.is_open())
    {
        cout << "Cant open file";
    }

}

What did i do wrong??

6
  • What did you do to run above program .? Commented Apr 6, 2017 at 5:13
  • Stick with the convention: argc and argv. You do konw the exe name counts, so that is arg 1. You say anything other than 1 arg is wrong but then open the 2nd arg anyway... Commented Apr 6, 2017 at 5:15
  • @radbrawler i use command line to run it first i g to disk D: then D: cd>New folder\ConsoleAp8\Debug then ConsoleAp8.exe test1.txt that's it. Commented Apr 6, 2017 at 5:17
  • @John3136 i thought the exe name count as argv[0] ?, argc just count the statement ,so the file name is first statement ?? Commented Apr 6, 2017 at 5:19
  • @Van. Right, but an array with 1 member (argc == 1) only has position 1. You say if (argc != 1) { print wrong } that implies you expect no args (just the exe name) Commented Apr 6, 2017 at 5:27

1 Answer 1

1

Well I changed the program a bit and it worked. Mainly it was argument length

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(int i ,char *a[])
{
    if (i != 2)
    {
        cout << "Wrong!!! "<<i;
    }
    fstream fp;
    fp.open(a[1]);
    if (!fp.is_open())
    {
        cout << "Cant open file";
    }
    return 0;
}

That worked for me.

edit- I ran it on ubuntu. I didn't had windows.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.