Error creating temp file (Creating a client/server application that the client streams WAV files from the server using DirectSound )

39 views Asked by At

For a project for my university I have to create a client/server application where the client and the server communicate through sockets and the client streams WAV files from the server using DirectSound API

when I am trying to play a WAV file I am getting this error "Error creating temp file"

that is the code for creating the temp file

// Receive the list of files from the server
    char buffer[256] = { 0 };
    int bytes_received = recv(socket_client, buffer, sizeof(buffer), 0);
    if (bytes_received == SOCKET_ERROR) {
        std::cout << "Error receiving file list" << std::endl;
        closesocket(socket_client);
        WSACleanup();
        return 1;
    }
    std::string file_list(buffer, bytes_received);

    std::cout << "Available files: " << std::endl << file_list << std::endl;

    // Ask the user to choose a file
    std::string chosen_file;
    std::cout << "Enter the name of the file you want to play: ";
    std::cin >> chosen_file;

    // Send the chosen file to the server
    if (send(socket_client, chosen_file.c_str(), chosen_file.size(), 0) == SOCKET_ERROR) {
        std::cout << "Error sending chosen file" << std::endl;
        closesocket(socket_client);
        WSACleanup();
        return 1;
    }
    // Receive the file size from the server
    int file_size;
    if (recv(socket_client, reinterpret_cast<char*>(&file_size), sizeof(file_size), 0) == SOCKET_ERROR) {
        std::cout << "Error receiving file size" << std::endl;
        closesocket(socket_client);
        WSACleanup();
        return 1;
    }

    // Create a temporary file to store the received data
    std::string file_path = "path/to/temp/file.wav";
    std::ofstream temp_file(file_path, std::ios::binary);
    if (!temp_file.is_open()) {
        std::cout << "Error creating temp file" << std::endl;
        closesocket(socket_client);
        WSACleanup();
        return 1;
    }

    // Receive the file from the server in chunks
    const int CHUNK_SIZE = 1024;
    char chunk[CHUNK_SIZE];
    int total_bytes_received = 0;
    while (total_bytes_received < file_size) {
        bytes_received = recv(socket_client, chunk, CHUNK_SIZE, 0);
        if (bytes_received == SOCKET_ERROR) {
            std::cout << "Error receiving file" << std::endl;
            temp_file.close();
            closesocket(socket_client);
            WSACleanup();
            return 1;
        }
        temp_file.write(chunk, bytes_received);
        total_bytes_received += bytes_received;
    }
    temp_file.close();
    std::cout << "File received: " << chosen_file << std::endl;
1

There are 1 answers

0
Chuck Walbourn On

For Win32, you'd use GetTempFileName to generate a temporary path and filename to use for your download.

In C++17, you can make use of std::filesystem's temp_directory_path.