繁体   English   中英

如何在 C++ (Xcode) 中写入文件

[英]How to write into a file in C++ (Xcode)

即使文件已经在正确的目录中,我也在努力写入用户提供的文件。 这是代码:

#include <iostream>
#include<fstream>
#include <string>
using namespace std;
int main() {
    string filename;
    cout<<"Enter file name"<< endl;
    cin>>filename;
    ofstream outfile;
    outfile.open(filename.c_str());
    outfile<< "Hello"<< endl;
    outfile.close();
    return 0;
}

我对 C++ 编程比较陌生,所以我不知道从哪里开始。 有任何想法吗? 提前谢谢各位。

怎么样:

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cout<<"Enter file name"<< std::endl;
    std::cin >> input;
    std::ofstream out(input.c_str());
    out << input;
    out.close();
    return 0;
}

并检查文件是否存在:

inline bool fileExists(const std::string& name) {
    ifstream f(name.c_str());
    return f.good();
}

另见问题 12774207

当前工作目录,您可以按照问题 298510的描述获取

#include <unistd.h>
char *getcwd(char *buf, size_t size);

在 POSIX 系统上,以及

#include <winbase.h>
DWORD WINAPI GetCurrentDirectory(
  _In_  DWORD  nBufferLength,
  _Out_ LPTSTR lpBuffer
);

在 Windows 系统上。

要更改当前工作目录,请使用

#include <unistd.h>
chdir(sDirectory.c_str());

在 POSIX 系统上,以及

 #include <winbase.h>
 SetCurrentDirectory(sDirectory.c_str());

在 Windows 系统上。

此外,如果您需要知道可执行文件的位置,以正确设置当前工作目录,您可以使用

#include <Libloaderapi.h>
TCHAR szExeFileName[MAX_PATH]; 
GetModuleFileName(NULL, szExeFileName, MAX_PATH);

在 Windows 和

#include <unistd.h> 
int get_exe_for_pid(char *buf, size_t bufsize) 
{
    char path[32];
    pid_t pid = getpid(); 
    sprintf(path, "/proc/%d/exe", pid);
    return readlink(path, buf, bufsize);
}

对于带有 /proc 的系统。 (Linux,免费的)

如果您使用的是 Mac,那就是

#include <sys/param.h>
#include <mach-o/dyld.h>

if ( _NSGetExecutablePath( chrarray_Buffer, &u32_BufferLength ))
{
    printf("An error occured while reading the executable path. Program terminated.\n") ;
    exit(EXIT_FAILURE) ;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM