dynamic 2d char array in c - c++

I want to take username and passwords from client and check that this username already didn't exist, but it doesn't work and this error happens:
Exception thrown at 0x51D20ED2 (ucrtbased.dll) in project3.exe: 0xC0000005:
Access violation reading location 0xCDCDCDCD.>
I don't know why?
This is my code:
void signup(char *input, char **usernames,int *userindex,char **passwords)
{
int check = 0;
char *ptr1,*ptr2;
ptr1 = (char*)malloc(strlen(input)*sizeof(char));
ptr2 = (char*)malloc(strlen(input)*sizeof(char));
strtok(input, " ");
strcpy(ptr1, strtok(NULL," "));
strcpy(ptr2, strtok(NULL," "));
for (int i = 1; i < *(userindex); i++)
{
if (!(strcmp(ptr1,usernames[i])))
{
check = 1;
printf("this user has already signed up\n");
break;
}
}
if (check == 0)
{
usernames[*(userindex)] = (char*)malloc((strlen(ptr1))* sizeof(char));
passwords[*(userindex)] = (char*)malloc((strlen(ptr2))* sizeof(char));
strcpy(usernames[*(userindex)], ptr1);
strcpy(passwords[*(userindex)], ptr2);
printf("%s\n%s\n%d\n", usernames[*(userindex)], passwords[*(userindex)], *(userindex));
*(userindex) = *(userindex)+1;
free(ptr1);
free(ptr2);
}
}
int main()
{
int quit = 0;
char *input, **usernames, **passwords;
int state, length, userindex = 1;
usernames = (char**)malloc(sizeof(char*));
passwords = (char**)malloc(sizeof(char*));
while (quit == 0)
{
int counter = 1;
char buffer;
input = (char*)malloc(sizeof(char));
printf("please enter your action\n");
do
{
buffer = getchar();
input = (char*)realloc(input, counter*sizeof(char));
input[counter - 1] = buffer;
counter++;
} while (buffer != '\n');
input = (char*)realloc(input, (counter)*sizeof(char));
input[counter - 1] = '\0';
state = action_decider(input);
switch (state)
{
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
usernames = (char**)realloc(usernames,userindex*sizeof(char*));
passwords = (char**)realloc(passwords,userindex*sizeof(char*));
signup(input, usernames, &(userindex), passwords);
break;
case 5:
break;
case 6:
quit = 1;
break;
case 7:
printf("you command nonsence!\n");
break;
}
}
return 0;
}

Related

Nested strtok in Arduinoproject

I'm coding a parser for my Arduinoproject. I have a long charArray that contains multiple "packages" in the form of:
# package beginns
adress
; seperating character
adress
; seperating character
command
; seperating character
data
* package ends
One input could be:
#A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*
The goal is to write a Parser that takes a charArray and splits it at one char ('#') and than a second time with another char (';'). The problem is that the outer splitting is only done once and than stopps. I think it has something to do with the pointer, but don't know what to do.
My Code:
void setup() {
Serial.begin(9600);
char test[] = "#A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*";
Serial.print("Test: ");
Serial.println(test);
Serial.println("--------------------");
parseCurrentStream(test);
Serial.println("-----------END_OF_CODE------------");
}
void parseCurrentStream(char* input){
int commandCount = getCountOfCharInString(input, '*');
package packageList[commandCount];
commandCount = 0;
char* piece = strtok(input, "#");
while (piece != NULL){
Serial.println(piece);
package pack = getPackage(piece);
printPackage(pack);
commandCount++;
piece = strtok(NULL, "#");
}
}
package getPackage(char* packageString){
Serial.println("---Start_Parsing---");
Serial.print("StringInput: ");
Serial.println(packageString);
bool corruptedData = false;
if(!isEndCharExisting(packageString)){
corruptedData = true;
}
// final Fields
char* receiver;
char* transmitter;
char command;
char* data;
bool empty;
char* piece = strtok(packageString, ";");
int counter;
while (piece != NULL && !corruptedData){
Serial.print(corruptedData);
Serial.print(" | Piece ");
Serial.print(counter);
Serial.print(": ");
Serial.println(piece);
switch(counter){
case 0:
if(strlen(piece) == 5){
receiver = piece;
} else {
corruptedData = true;
}
break;
case 1:
if(strlen(piece) == 5){
transmitter = piece;
} else {
corruptedData = true;
}
break;
case 2:
if(strlen(piece) == 1){
command = piece[0];
} else {
corruptedData = true;
}
break;
case 3:
if(strlen(piece) == sizeOfCommand(command)){
data = piece;
} else {
corruptedData = true;
}
break;
case 4:
if(!(strlen(piece) == 1 && piece[0] == '*')){
corruptedData = true;
}
break;
default:
corruptedData = true;
break;
}
counter++;
piece = strtok(NULL, ";");
}
struct package finalPackage;
if(corruptedData){
finalPackage = {receiver, transmitter, command, data, true};
} else {
finalPackage = {receiver, transmitter, command, data, false};
}
Serial.println("---End_Parsing---");
return finalPackage;
}
Output:
Test: #A0001;B0001;A;2456;*#A0002;B0002;B;7615;*#A0003;B0003;C;8943;*
--------------------
A0001;B0001;A;2456;*
---Start_Parsing---
StringInput: A0001;B0001;A;2456;*
0 | Piece 0: A0001
0 | Piece 1: B0001
0 | Piece 2: A
0 | Piece 3: 2456
0 | Piece 4: *
---End_Parsing---
Package:
A0001
B0001
A
2456
0
-----------------
-----------END_OF_CODE------------
You can see that for the first iteraton it works perfectly, but the second "string" (#A0002;B0002;B;7615;*) is not parsed...
When i'm not using my function getPackage() the substrings are printed as expected. I have found some advice to copy the char before inserting it to the function but this also didn't help.
char pieceCopy[strlen(piece)];
strcpy(pieceCopy, piece);
Because you are splitting for different tokens at the same time (both in parseCurrentStream and in getPackage), you are messing up the internal state of strtok. However, using one strtok_r for each tokenization, you can provide a pointer to a char pointer, that each different strtok_r can use to save its current state. See the example in the link provided. strtok_r is especially useful in multi-threaded environments.
char *strtok_r(char *str, const char *delim, char **saveptr);
char input[] = "the quick brown fox";
char* token;
char* rest;
char* str = input;
while ((token = strtok_r(str, " ", &rest))) {
str = NULL;
printf("%s\n", token);
}
Thanks for all of your support!!!
For me the solution of #Gerhardh worked perfectly.
The strsep() was availbale for me.
My code looks like this now:
void parseCurrentStream(char* input){
int commandCount = getCountOfCharInString(input, '*');
char* piece;
char* string;
string = strdup(input);
while( (piece = strsep(&string,"#")) != NULL ){
if(strlen(piece) > 0){
package pack = getPackage(piece);
printPackage(pack);
}
}
}
package getPackage(char* packageString){
Serial.println("---Start_Parsing---");
Serial.print("StringInput: ");
Serial.println(packageString);
bool corruptedData = false;
// final Fields
char* receiver;
char* transmitter;
char command;
char* data;
bool empty;
//char* piece = strtok(packageString, ";");
int counter = 0;
char* piece;
char* string;
string = strdup(packageString);
while ((piece = strsep(&string,";")) != NULL){
Serial.print(corruptedData);
Serial.print(" | Piece ");
Serial.print(counter);
Serial.print(": ");
Serial.println(piece);
switch(counter){
case 0:
if(strlen(piece) == 5){
receiver = piece;
} else {
corruptedData = true;
}
break;
case 1:
if(strlen(piece) == 5){
transmitter = piece;
} else {
corruptedData = true;
}
break;
case 2:
if(strlen(piece) == 1){
command = piece[0];
} else {
corruptedData = true;
}
break;
case 3:
if(strlen(piece) == sizeOfCommand(command)){
data = piece;
} else {
corruptedData = true;
}
break;
case 4:
if(!(strlen(piece) == 1 && piece[0] == '*')){
corruptedData = true;
}
break;
default:
corruptedData = true;
break;
}
counter++;
}

How to convert int type number/letter to char and *char?

I am using LittleFS library and ESP32 on arduino IDE.
I am reading a file using the example readFile function of LittleFS but I am trying to convert it for my needs.
The text written to the file is of this form:
LettersAndNumbersMax30&LettersAndNumbersMax30&00&00&01&01
Seperated by &. 2 text values of max 30 characters and 4 integers.
I want to build:
char *mytest1 containing the first text
char *mytest2 containing the second text
int mytest3 containing the first integer (2digits)
int mytest4 containing the second integer (2digits)
int mytest5 containing the third integer (2digits)
int mytest5 containing the forth integer (2digits)
file.read() returns and integer always. for example 38 for &.
void readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
Its fairly straightforward. Test each byte read and act accordingly. Code below doesn't handle signs nor negative numbers. It also doesn't check if there are only digits for integers in the file.
#include ....
struct record_t
{
char myState1[31];
char myState2[31];
int myState3;
int myState4;
int myState5;
int myState6;
};
record_t record;
bool readFile(fs::FS &fs, const char * path);
void setup()
{
// ...
}
void loop()
{
//...
if (readFile(/*...*/))
{
Serial.printf("file reads OK\r\n");
//...
}
}
bool readFile(fs::FS &fs, const char * path)
{
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
int state = 0;
int index = 0;
// clear record.
record.myState1[0] = 0;
record.myState2[0] = 0;
record.myState3 = 0;
record.myState4 = 0;
record.myState5 = 0;
record.myState6 = 0;
bool valid = false;
for (int i = file.read(); i != -1; i = file.read())
{
char c = i & 0xFF;
Serial.write(c); // file.read() returns an int, that's why Serial.write()
// was printing numbers.
switch(state)
{
case 0:
if (index > sizeof(record.myState1) - 1) // avoid buffer overflow
index = sizeof(record.myState1) - 1;
if (c != '&')
{
record.myState1[index++] = c;
}
else
{
record.myState1[index] = 0;
++state;
index = 0;
}
break;
case 1:
if (index > sizeof(record.myState2) - 1) // avoid buffer overflow
index = sizeof(record.myState2) - 1;
if (c != '&')
{
record.myState2[index++] = c;
}
else
{
record.myState2[index] = 0;
++state;
index = 0;
}
break;
case 2:
if (c != '&')
record.myState3 = record.myState3 * 10 + (c - '0');
else
++state;
break;
case 3:
if (c != '&')
record.myState4 = record.myState4 * 10 + (c - '0');
else
++state;
break;
case 4:
if (c != '&')
record.myState5 = record.myState5 * 10 + (c - '0');
else
++state;
break;
case 5:
valid = true;
if (c != '&')
record.myState6 = record.myState6 * 10 + (c - '0');
else
++state;
break;
default: // reaching here is an error condition? You decide.
return false;
}
}
file.close();
if (!valid)
{
// clear record.
record.myState1[0] = 0;
record.myState2[0] = 0;
record.myState3 = 0;
record.myState4 = 0;
record.myState5 = 0;
record.myState6 = 0;
}
return valid;
}
file.read returns integer. So the integer is printed.
You to convert it to the string.
while(file.available()){
char s[2] = {0};
s[0] = file.read();
Serial.write(s);
}

Setting NULL causes lag with [MAX_STRING_LENGTH] = {'\0'};

I thought it would be a good best practice to search thru my code for any references like ..
char buf[MAX_STRING_LENGTH];
... and replace them with ...
char buf[MAX_STRING_LENGTH] = {'\0'};
Doing a search in the code I have a number that are set to null (around 239) and others that are not (1,116).
When I replaced the remaining 1,116 instances with char buf[MAX_STRING_LENGTH] = {'\0'}; and pushed the code live the game was noticeably laggy.
Reverting the change removed the lag.
Can someone explain why setting these to null would cause the game to lag while running?
Example code setting to Null
void do_olist(Character *ch, char *argument, int cmd)
{
int header = 1;
int type = -1;
int wear_bit = -1;
int i = 0;
int inclusive;
int zone = -1;
int yes_key1 = 0;
int yes_key2 = 0;
int yes_key3 = 0;
int count = 0;
Object *obj;
bool found = false;
char key1 [MAX_STRING_LENGTH] = {'\0'};
char key2 [MAX_STRING_LENGTH] = {'\0'};
char key3 [MAX_STRING_LENGTH] = {'\0'};
char buf [MAX_STRING_LENGTH];
argument = one_argument(argument, buf);
if (!*buf)
{
ch->send("Selection Parameters:\n\n");
ch->send(" +/-<object keyword> Include/exclude object keyword.\n");
ch->send(" <zone> Objects from zone only.\n");
ch->send(" <item-type> Include items of item-type.\n");
ch->send(" <wear-bits> Include items of wear type.\n");
ch->send("\nExample: olist +sword -rusty weapon 10\n");
ch->send("will only get non-rusty swords of type weapon from zone 10.\n");
return;
}
while (*buf)
{
inclusive = 1;
if (strlen(buf) > 1 && isalpha(*buf) &&
(type = index_lookup(item_types, buf)) != -1)
{
argument = one_argument(argument, buf);
continue;
}
if (strlen(buf) > 1 && isalpha(*buf) &&
(wear_bit = index_lookup(wear_bits, buf)) != -1)
{
argument = one_argument(argument, buf);
continue;
}
if (isdigit(*buf))
{
if ((zone = atoi(buf)) >= MAX_ZONE)
{
ch->send("Zone not in range 0..99\n");
return;
}
argument = one_argument(argument, buf);
continue;
}
switch (*buf)
{
case '-':
inclusive = 0;
case '+':
if (!buf [1])
{
ch->send("Expected keyname after 'k'.\n");
return;
}
if (!*key1)
{
yes_key1 = inclusive;
strcpy(key1, buf + 1);
}
else if (!*key2)
{
yes_key2 = inclusive;
strcpy(key2, buf + 1);
}
else if (*key3)
{
ch->send("Sorry, at most three keywords.\n");
return;
}
else
{
yes_key3 = inclusive;
strcpy(key3, buf + 1);
}
break;
case 'z':
argument = one_argument(argument, buf);
if (!isdigit(*buf) || atoi(buf) >= MAX_ZONE)
{
ch->send("Expected valid zone after 'z'.\n");
return;
}
zone = atoi(buf);
break;
}
argument = one_argument(argument, buf);
}
*b_buf = '\0';
for (obj = full_object_list; obj; obj = obj->lnext)
{
if (zone != -1 && obj->zone != zone)
continue;
if (type != -1 && obj->obj_flags.type_flag != type)
continue;
if (wear_bit != -1)
{
for (i = 0; (*wear_bits[i] != '\n'); i++)
{
if (IS_SET(obj->obj_flags.wear_flags, (1 << i)))
{
if (i != wear_bit)
continue;
else
found = true;
}
}
if (found)
found = false;
else
continue;
}
if (*key1)
{
if (yes_key1 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key1))
continue;
else if (!yes_key1 && strcasestr(const_cast<char*> (obj->getName().c_str()), key1))
continue;
}
if (*key2)
{
if (yes_key2 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key2))
continue;
else if (!yes_key2 && strcasestr(const_cast<char*> (obj->getName().c_str()), key2))
continue;
}
if (*key3)
{
if (yes_key3 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key3))
continue;
else if (!yes_key3 && strcasestr(const_cast<char*> (obj->getName().c_str()), key3))
continue;
}
count++;
if (count < 200)
olist_show(obj, type, header);
header = 0;
}
if (count > 200)
{
sprintf(buf, "You have selected %d objects (too many to print all at once).\n",
count);
ch->send(buf);
//return;
}
else {
sprintf(buf, "You have selected %d objects.\n",
count);
ch->send(buf);
}
page_string(ch->desc, b_buf);
}
I took the advice to replace instances of ...
char buf[MAX_STRING_LENGTH] = {'\0'};
with ...
char buf[MAX_STRING_LENGTH]; *buf = 0;

Reference cannot be initialized/expression must have type class

I'm doing a quick binary tree program as a homework, but I am getting weird errors that I can't seem to figure out how to fix. Normally I'm programming in C#, and C is just slightly different but different enough for me to get confused.
Here is the code that is giving the error:
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
And here is the whole script:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct stub
{
char crown[51];//some custom name - can be empty
float b;//comparable value for tree sort
int c;//limited by maxint
stub *l;//left node(normally smaller "b" value than this node)
stub *r;//right node(normally bigger "b" value than this node)
};
stub *stubList[255];//empty list of a stub array with a safe casual amount
int arraySize = 0;
stub *head = NULL;//main stub(first)
stub *latest = NULL;//latest stub
stub *st = NULL;//used for creating and checking
FILE *fs = NULL;
char fileName[255];
int maxint = 20;//for var 'c'
void BTreeNodeToArray(stub *s) {
stubList[arraySize] = s;
arraySize++;
}
void Swap(stub &s1, stub &s2) {
stub temp = s2;
s1 = s2;
s2 = temp;
}
int MaxMin(int num) {
int clampedInt = num;
if (num < 0) clampedInt = 0;
else if (num > maxint) clampedInt = maxint;
return clampedInt;
}
//Create a completely new stub with crown, b, and c variables being filled here
void CreateElement() {
st = new stub;
printf("Adding information for node:\n");
printf("Node name: "); gets_s(st->crown);
printf("\n");
float f;
printf("Node float value (B): "); scanf_s("%f", &f);
st->b = f;
printf("\n");
int d;
printf("Node integer value (C): "); scanf_s("%d", &d);
st->c = d;
printf("\n");
st->c = MaxMin(st->c);
st->l = NULL;
st->r = NULL;
}
//creates the very first stub(root/head)
void CreateFirst() {
printf("First in tree. Adding root node...\n");
CreateElement();
head = st;
latest = head;
BTreeNodeToArray(head);
printf("Added head stub\ncrown: %s\nValue: %f\nExtra: %d", head->crown, head->b, head->c);
getchar();
getchar();
}
void AddStub() {
if (head == NULL) {
CreateFirst();
}
else {
CreateElement();//create newest node
latest = st;
st = head;
int depth = 0;
while (1) {
if ((latest->b <= st->b)) {//choose left if true
printf("Went left\n");
depth++;
if (st->l == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->l = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (left)\n");
st = st->l;
}
}
else {//choose right
printf("Went right\n");
depth++;
if (st->r == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->r = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (right)\n");
st = st->r;
}
}
}
}
}
void ViewArray() {
for (int i = 0; i < arraySize; i++)
{
printf_s("Node [%d]:\n\tCrown: %s\n\tweight: %f\n\tExta value(0 - %d): %d\n", i, stubList[i]->crown, stubList[i]->b, maxint, stubList[i]->c);
}
getchar();
}
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
void ProcessArray() {
char c = ' ';
int found = 0;
printf("Process with character: \n"); c = _getch();
if (arraySize <= 0) {
printf("No List!");
return;
}
char chkstr[5];
for (short i = 0; i < 5; i++)//simple assign to a 'string' 5 times
{
chkstr[i] = c;
}
for (int i = 0; i < arraySize; i++)
{
if (strstr(stubList[i]->crown, chkstr) != NULL) {
// contains
printf("B = %f at [%d] \n", stubList[i]->b, i);
found++;
}
}
if (found > 0) {
printf("---Found: %d with character %c---", found, c);
}
else {
printf("No elements found with '%c'", c);
}
getchar();
}
void ExportArray() {
FILE *fs = NULL;
char fileName[255];
errno_t err;
printf("Save to file as: \n"); gets_s(fileName);
if (strlen(fileName) == 0) {
printf("Failed to create file. File name empty!");
_getch();
_getch();
}
err = fopen_s(&fs, fileName, "wb");
if (err != 0) {
printf("Failed to create file!!!");
_getch();
_getch();
return;
}
for (int i = 0; i < arraySize; i++)
{
int written = fwrite(&stubList[i], sizeof(stub), 1, fs);
//fwrite(&gr[i], sizeof(student), 1, fs);
}
int numclosed = _fcloseall();
printf("Exported to file: %s", fileName);
getchar();
}
void CleanReset() {//reset all values and release memory (function used for import)
for (int i = 0; i < arraySize; i++)
{
delete stubList[i];
}
arraySize = 0;
st = NULL;
head = NULL;
latest = NULL;
}
void ImportArray() {
FILE *fs = NULL;
char fname[255];
errno_t err;
printf("Open FIle: "); gets_s(fname);
err = fopen_s(&fs, fname, "rb");
if (err == 0) {
CleanReset();
fseek(fs, 0, SEEK_END);
long size = ftell(fs);
arraySize = size / sizeof(stub);//get amount of students saved
fseek(fs, 0, SEEK_SET);
int i = 0;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
while (!feof(fs)) {
i++;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
}
printf("File data imported. Size: %d", arraySize);
getchar();
return;
}
printf("Failed to import file!!!");
getchar();
}
void main()
{
system("chcp 65001");//use utf8
char izb = 'i';
while (izb != '0') {
system("cls");
printf_s("1. Add stub\n");
printf_s("2. View Array\n");
printf_s("3. Sort Array\n");
printf_s("4. Process\n");
printf_s("5. Export array to file\n");
printf_s("6. Import array from file\n");
printf_s("0. Exit\n\n");
printf_s("Choose action:\n"); izb = _getch();
switch (izb)
{
case '1':
AddStub();
break;
case '2':
ViewArray();
break;
case '3':
SortArray();
break;
case '4':
ProcessArray();
break;
case '5':
ExportArray();
break;
case '6':
ImportArray();
break;
case '0':
//Exit();
break;
}
}
}
The error is that you want to pass a stub * to a function that wants a stub &. The first one is a pointer, the second one is a reference.
You have two options.
First option (imho recommended):
Change your swap function to accept pointers instead of references.
void Swap(stub *s1, stub *s2) {
stub temp = *s2;
*s1 = *s2;
*s2 = temp;
}
Second option:
Dereference the parameters before passing to swap:
Swap(*(stubList[i]), *(stubList[i + 1]));
You have to undestand that the datatype in your list is a pointer to stub, the function Swap wants a reference, which are different things in C++.
For a better understanding I recommend reading this: https://www.geeksforgeeks.org/pointers-vs-references-cpp/

detecting a hard drive in the IDE

I am trying to detect the drive letter in Windows. Drive is a primary drive in second IDE channel. I am using GetLogicalDrives().
But this does not tell me I am accessing IDE primary drive.
Here is an example:
#include <cstdint>
#include <windows.h>
#include <cstdio>
const char* GetTypeOfDrive(const char* Drive)
{
const char* Result = NULL;
unsigned int DriveType = GetDriveType(Drive);
switch(DriveType)
{
case DRIVE_FIXED:
Result = "Hard disk";
break;
case DRIVE_CDROM:
Result = "CD/DVD";
break;
case DRIVE_REMOVABLE:
Result = "Removable";
break;
case DRIVE_REMOTE:
Result = "Network";
break;
default:
Result = "Unknown";
break;
}
return Result;
}
int GetLogicalDrivesList(char Drives[26])
{
int Res = 0;
DWORD DrivesMask = GetLogicalDrives();
for (int I = 0; I < 26; ++I)
{
if (DrivesMask & (1 << I))
{
Drives[Res++] = 'A' + I;
}
}
return Res;
}
int main()
{
char temp[4];
char drives[26];
int drive_count = GetLogicalDrivesList(drives);
for (int i = 0; i < drive_count; ++i)
{
sprintf(temp, "%c:/", drives[i]);
printf("%c is a %s\n", drives[i], GetTypeOfDrive(temp));
}
}