c - 我在 Windows 中写入文件时遇到问题?

标签 c winapi file-io

我正在尝试创建一个文本文件并向其写入内容,但是当我打开该文本文件时,输出出现错误。

示例:

Please enter number of students?
2
Please Enter details of the Students in the Following sequence: Name Age GPA
alex  18 3.2
dan  21 3.5

输出:

tttttttttkkkkkkkkksssssssssss

代码:

#include "stdafx.h"
#include<stdio.h>
#include<Windows.h>

struct Student {
    WCHAR name[20];
    int age;
    float gpa;
};

int _tmain(int argc, _TCHAR* argv[])
{
    struct Student St;
    int NumOfStu;
    printf("Please enter number of students\n");
    scanf("%d" , &NumOfStu);

    HANDLE f = CreateFile(L"d:\\SPR2.txt" , GENERIC_WRITE , 0 , NULL , CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL);
    if(f == INVALID_HANDLE_VALUE)
    {
        printf("Could not Create The File\n");
        return 0;
    }

    printf("Please Enter details of the Sutdents in the Following sequence: Name Age GPA\n");

    DWORD actual;

    for(int i=0 ;i<NumOfStu;i++)
    {
        scanf("%s %d %f" , &St.name , &St.age , &St.gpa );
        WriteFile(f ,  , sizeof(struct Student) , &actual , NULL); 
    }
    CloseHandle(f);

    return 0;
}

最佳答案

    scanf("%s %d %f" , &St.name , &St.age , &St.gpa );

name 已经衰减为指针,您不应该将 & 与它一起使用。

此外,它是一个宽字符串,这是 scanf 所不希望的。所以你会腐败。

关于c - 我在 Windows 中写入文件时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9944710/

相关文章:

c++ - 如何在控制台 Win32 应用程序中设置计时器?

c++ - 使用模块句柄挂起模块

c - 读取 SQLite header

C++:如何读取和写入文件夹

c++ - 一维数组衰减为指针,但二维数组不会衰减,为什么?

c - ARM 处理器如何区分负数和正数?

c++ - 如何将权限从一个主要用户 token 复制到另一个主要用户 token ?

c - Pthread condvar 习语

C 中的命令行解释器

c - 如何有效地从 C 文件中检索数据