the file extension in StringCbCatN() to get all the files name withextension - c

Code that I am running now:
int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError;
LPSTR DirSpec;
size_t length_of_arg;
int i,j;
char cd[256],schar[500];
FILE *fp;
DirSpec = (LPSTR) malloc (BUFSIZE);
// Check for command-line parameter; otherwise, print usage.
if(argc != 2)
{
printf("Usage: Test <dir>\n");
return 2;
}
// Check that the input is not larger than allowed.
//scanf("%s",argv[1]);
StringCbLength(argv[1], BUFSIZE, &length_of_arg);
if (length_of_arg > (BUFSIZE - 2))
{
printf("Input directory is too large.\n");
return 3;
}
printf ("Target directory is %s.\n", argv[1]);
StringCbCopyN (DirSpec, BUFSIZE, argv[1], length_of_arg+1);
StringCbCatN (DirSpec, BUFSIZE, "\\namefile.b11", 18);
hFind = FindFirstFile(DirSpec, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u.\n", GetLastError());
return (-1);
}
else
{
printf ("First file name is %s.\n", FindFileData.cFileName);
fp=fopen(DirSpec,"rb");
for(i=0;i< 8;i++)
{
schar[i]= fgetc(fp);//get each character from file
}
if ( i > 7 )
{
cd[i]=schar[6]*65336+schar[5]*256+schar[4];
printf("%d",cd[i]);
}
// List all the other files in the directory.
while (FindNextFile(hFind, &FindFileData) != 0)
{
printf ("Next file name is %s.\n", FindFileData.cFileName);
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
printf ("FindNextFile error. Error is %u.\n", dwError);
return (-1);
}
}
free(DirSpec);
getchar();
return (0);
}
This is working fine. If I concatinate the file name directly by using StringCbCatN().
But for every file I need to change the file name.which I don't want. Is it possible to print the file with file extension?

Related

C function call is giving me a "too many arguments" error

I'm getting a "too many arguments in function call" error in my C program. The error occurs at a line where I'm calling a function that has a fixed number of arguments. I'm not sure why I'm getting this error, as I'm not passing in more arguments than the function expects. Here's the code where the error occurs:
if (mkdir(path, 0777) == -1)
Here is full code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#define BUF_SIZE 1024
#define MAX_ARGS 10
// Print the usage message for the program
void print_usage() {
fprintf(stderr, "Usage: syscalls <command> [arguments]\n");
}
// Read the contents of a file and write them to stdout
int read_file(const char *path) {
static char buf[BUF_SIZE];
int fd = open(path, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno));
return 1;
}
ssize_t num_read;
while ((num_read = read(fd, buf, BUF_SIZE)) > 0) {
if (write(STDOUT_FILENO, buf, num_read) != num_read) {
fprintf(stderr, "Failed to read %s: %s\n", path, strerror(errno));
return 1;
}
}
if (num_read == -1) {
fprintf(stderr, "Failed to read %s: %s\n", path, strerror(errno));
return 1;
}
return 0;
}
// Write a set of lines to a file
int write_file(const char *path, char *lines[], int num_lines) {
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno));
return 1;
}
int total_bytes = 0;
for (int i = 0; i < num_lines; i++) {
const char *line = lines[i];
size_t len = strlen(line);
ssize_t num_written = pwrite(fd, line, len, total_bytes);
if (num_written == -1) {
fprintf(stderr, "Failed to write to %s: %s\n", path, strerror(errno));
return 1;
}
total_bytes += num_written;
}
printf("Wrote %d B\n", total_bytes);
return 0;
}
// Create a directory
int make_directory(const char *path) {
if (mkdir(path, 0777) == -1) {
if (errno == EEXIST) {
fprintf(stderr, "%s already exists\n", path);
} else {
fprintf(stderr, "Failed to create %s: %s\n", path, strerror(errno));
}
return 1;
}
return 0;
}
// List the contents of a directory
int list_directory(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "Failed to open directory %s: %s\n", path, strerror(errno));
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
if (closedir(dir) == -1) {
fprintf(stderr, "Failed to close directory %s: %s\n", path, strerror(errno));
return 1;
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
print_usage();
return 1;
}
char *command = argv[1];
if (strcmp(command, "read") == 0) {
if (argc != 3) {
print_usage();
return 1;
}
return read_file(argv[2]);
} else if (strcmp(command, "write") == 0) {
if (argc < 4 || argc > MAX_ARGS + 2) {
print_usage();
return 1;
}
return write_file(argv[2], argv + 3, argc - 3);
} else if (strcmp(command, "mkdir") == 0) {
if (argc != 3) {
print_usage();
return 1;
}
return make_directory(argv[2]);
} else if (strcmp(command, "ls") == 0) {
if (argc != 3) {
print_usage();
return 1;
}
return list_directory(argv[2]);
} else {
print_usage();
return 1;
}
}
I am getting this error in terminal:
syscalls.c: In function 'write_file':
syscalls.c:54:31: warning: implicit declaration of function 'pwrite' [-Wimplicit-function-declaration]
ssize_t num_written = pwrite(fd, line, len, total_bytes);
^~~~~~
syscalls.c: In function 'make_directory':
syscalls.c:67:9: error: too many arguments to function 'mkdir'
if (mkdir(path, 0777) == -1) {
^~~~~
In file included from c:\mingw\include\unistd.h:56:0,
from syscalls.c:3:
c:\mingw\include\io.h:516:38: note: declared here
_CRTIMP __cdecl __MINGW_NOTHROW int mkdir (const char *);
Please help me to resolve this issue. Thank you
mkdir() is not specified in the C standard. It is specified in the POSIX standard, which is more or less a superset of the C standard.
This declaration of mkdir():
c:\mingw\include\io.h:516:38: note: declared here
_CRTIMP __cdecl __MINGW_NOTHROW int mkdir (const char *);
is the Microsoft version of the function, which takes a single argument, and does not conform to the POSIX standard.
From Microsoft's page:
The Microsoft-implemented POSIX function name mkdir is a deprecated
alias for the _mkdir function.
int _mkdir(
const char *dirname
);
Possible fix:
#ifdef _CRTIMP
#define mkdir(d,m) (mkdir)(d)
#endif
Credit: #chqrlie

C programming, copying from one file to another using command line arguments

This is my code
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Missing arguments\n");
return -1;
}
// Check if buffer is valid before reading anything
int bufferSize = atoi(argv[3]);
if (!bufferSize || bufferSize < 1) {
printf("Invalid buffer size\n");
return -1;
}
printf("*** Copying from '%s' to '%s' (Buffer size: %dB) ***\n",
argv[1], argv[2], bufferSize);
// READ SOURCE FILE
FILE *inputFile = fopen(argv[1], "r");
if (!inputFile) {
printf("Error opening source file\n");
return -1;
}
// READ DESTINATION FILE
FILE *outputFile = fopen(argv[2], "w");
if (!outputFile) {
printf("Error opening destination file\n");
return -1;
}
int buffer[bufferSize];
int bytes;
do {
bytes = fread(buffer, 1, bufferSize, inputFile);
if (fwrite(buffer, 1, bytes, outputFile) != bytes) {
printf("Error writing into destination file\n");
return -1;
}
} while (bytes > 0);
fclose(inputFile);
fclose(outputFile);
return 0;
}
But when I try to exe the file it doesn't work. What could be the problem?
Here's the command line:
/Users/jurajc/Documents/Program/C/L1\ 1/C_program/c_program file.txt fileCopy.txt 512
*** Copying from 'file.txt' to 'fileCopy.txt' (Buffer size: 512B) ***
Error opening source file
The input file file.txt cannot be opened: either because it is not present in the current directory or because you do not have read access to it.
You should output more informative error messages. Note also these problems:
if (!bufferSize || bufferSize < 1) is a redundant test. if (bufferSize < 1) is sufficient.
the error messages should be output to stderr
the files should be open in binary mode to reliably copy all file types on legacy systems.
the read/write loop is incorrect: you should stop when fread returns 0 before attempting to write 0 elements to the output file.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr, "Missing arguments\n");
return -1;
}
// Check if buffer is valid before reading anything
int bufferSize = atoi(argv[3]);
if (bufferSize < 1) {
fprintf(stderr, "Invalid buffer size: %s\n", argv[3]);
return -1;
}
printf("*** Copying from '%s' to '%s' (Buffer size: %dB) ***\n",
argv[1], argv[2], bufferSize);
// READ SOURCE FILE
FILE *inputFile = fopen(argv[1], "rb");
if (!inputFile) {
fprintf(stderr, "Error opening source file %s: %s\n",
argv[1], strerror(errno));
return -1;
}
// READ DESTINATION FILE
FILE *outputFile = fopen(argv[2], "wb");
if (!outputFile) {
fprintf(stderr, "Error opening destination file %s: %s\n",
argv[2], strerror(errno));
return -1;
}
int buffer[bufferSize];
int bytes;
while ((bytes = fread(buffer, 1, bufferSize, inputFile)) != 0) {
if (fwrite(buffer, 1, bytes, outputFile) != bytes) {
fprintf(stderr, "Error writing into destination file: %s\n", strerror(errno));
return -1;
}
}
fclose(inputFile);
fclose(outputFile);
return 0;
}

How to Write Differences in Two Text Files to Another Text File in C?

I'd like to write a program that compares two files and writes every byte in file one that is different from file two into a third file. I want to compare the files byte by byte and write any differing single bytes to the third file. I'm not very familiar with file I/O. Can someone give me an example program that accomplishes this task?
This is what I have so far:
int main(int argc, char *argv[]) {
int file1, file2, file1size, file2size;
// int difference1, difference2;
char buf;
if (argc != 3){
fprintf(stderr, "Usage %s <file1> <file2>", argv[0]);
exit(1);
}
if ((file1 = open(argv[1], 0400)) < 0) { //read permission for user on file source
fprintf(stderr, "Can't open source");
exit(1);
}
if ((file2 = open(argv[2], 0400)) < 0) { //read permission for user on file source
fprintf(stderr, "Can't open source");
exit(1);
}
file1size = lseek(file1, (off_t) 0, SEEK_END);
printf("File 1's size is %d\n", file1size);
file2size = lseek(file2, (off_t) 0, SEEK_END);
printf("File 2's size is %d\n", file2size);
}
I'm not sure how to compare file1 and file2's bytes and then write the differences to another file.
This is close to what you are looking for.
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *file1 = fopen(argv[1], "r");
FILE *file2 = fopen(argv[2], "r");
int i;
for(i = 0; !feof(file1) || !feof(file2); i++) {
int byte1 = getc(file1);
int byte2 = getc(file2);
if(byte1 != byte2) {
printf("%d %d %d\n", i, byte1, byte2);
}
}
return 0;
}
It takes the two files as command line arguments and compares the two byte-by-byte. If two bytes are different, it printf the character #, and the ASCII values of the two characters. -1 means EOF was already reached.
You'll have to (understand and) adapt this to the output format you want. (I'm assuming this is homework.)
feof tests for end-of-file.
getc gets the next character (byte) from the file. It is -1 if the end of the file has been reached.
And you seem already to know what printf does.
This does what you want, compiles, and runs,
#include <stdio.h>
int main(int argc, char *argv[])
{
int offset;
int argi=1;
int ch1, ch2;
FILE *fh1, *fh2, *fh3=stdout;
FILE *fh4=stdout;
if( argc<3 ) {
printf("usage: diff <file> <file> { <outfile> }\n"); return(1);
}
if(argi<argc) {
if(!(fh1 = fopen(argv[argi], "r"))) {
printf("cannot open %s\n",argv[argi]); return(2);
}
}
if(++argi<argc) {
if(!(fh2 = fopen(argv[argi], "r"))) {
printf("cannot open %s\n",argv[argi]); return(3);
}
}
if(++argi<argc) {
if(!(fh3 = fopen(argv[argi], "w+"))) {
printf("cannot open %s\n",argv[argi]); return(4);
}
}
if(++argi<argc) {
//duplicate output to a second file?
if(!(fh4 = fopen(argv[argi], "r"))) {
printf("cannot open %s\n",argv[argi]); return(3);
}
}
for(offset = 0; (!feof(fh1)) && (!feof(fh2)); offset++)
{
ch1=ch2='-';
if(!feof(fh1)) ch1 = getc(fh1);
if(!feof(fh2)) ch2 = getc(fh2);
if(ch1 != ch2) {
fprintf(fh3,"%d:%c %c\n", offset, ch1, ch2);
//additional file here
}
else {
fprintf(fh3,"%c\n", ch1);
//additional file here
}
}
return 0;
}
More typically, you would read entire lines using fgets, and strcmp to compare the lines. Here is how,
char str1[1024], str2[1024];
...
for(offset = 0; (!feof(fh1)) && (!feof(fh2)); offset++)
{
strcpy(str1,"-");strcpy(str2,"-");
if(!feof(fh1)) fgets(str1,sizeof(str1),fh1);
if(!feof(fh2)) fgets(str2,sizeof(str1),fh2);
if(strcmp(str1,str2)!=0)
fprintf(fh3,"%d:%s %s", offset, str1, str2);
else
fprintf(fh3,"%c", str1);
}

client server in c- file transfer issue for larger files

The below code works fine for smaller files where the last packet contains data less than maximum length, the function exit properly by displaying file received.
How ever if the last packet or buffer of file being transmitted contains exact number as the size of receiving buffer array 512 in my case. then th program keeps waiting for next packet.
All files with size multiple of 512 in my case stuck.
Below is the code:
CLIENT code for receiving:
void receiveFile() {
printf("inside receiveFile method\n");
char* fr_name = "final.txt";
int i;
FILE *fr = fopen(fr_name, "a");
int LENGTH = 512;
int fileLength=0;
char revbuf[LENGTH];
if (fr == NULL) {
printf("File %s Cannot be opened.\n", fr_name);
} else {
printf("starting to write the file\n");
bzero(revbuf, LENGTH);
int fr_block_sz = 0;
i=0;
while ((fr_block_sz = recv(4, revbuf, LENGTH, 0)) > 0) {
fileLength+=fr_block_sz;
i++;
printf("Received buffer: %d, %d\n",fr_block_sz,i);
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if (write_sz < fr_block_sz) {
error("File write failed.\n");
}
bzero(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512) {
break;
}
}
if (fr_block_sz < 0) {
if (errno == EAGAIN) {
printf("recv() timed out.\n");
} else {
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
}
}
printf("FILE RECEIVED....Total Bytes received:%d \n",fileLength);
}
fclose(fr);
}
Server for Receiving the file:
void sendFile() {
printf("inside sendFile method\n");
char* fs_name = "mb.txt";
int LENGTH = 512;
int sfileLength=0;
char sdbuf[LENGTH];
int i=0;
printf("[Client] Sending %s to the Server... \n", fs_name);
FILE *fs = fopen(fs_name , "r");
if (fs == NULL) {
perror("ERROR: File not found.\n");
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while ((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0) {
i++;
printf("Sent:%d , %d \n", fs_block_sz,i);
sfileLength+=fs_block_sz;
if (send(4, sdbuf, fs_block_sz, 0) < 0) {
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n",
fs_name, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("File sent.... Total Bytes:%d\n", sfileLength);
fclose(fs);
}
if (fr_block_sz == 0 || fr_block_sz != 512) {
break;
}
Remove this code. The first part of the test can never be true due to the 'while' condition, and the second part is unnecessary for the same reason.

Get Output of system("insmod mmodule.ko")

I want to run shell command in C program and get stdout output.
I did it in this function:
int run_shell_cmd_nout(const char* cmd)
{
FILE *fp;
char out[4096] = {0};
char str[256] = {0};
char full_cmd[1024] = {0};
int result = 0;
// Compose full shell command
if (!sprintf(full_cmd, "/system/bin/%s", cmd))
{
printf("Failed to compose full shell command\n");
return -1;
}
// Open the command for reading.
fp = popen(full_cmd, "r");
if (fp == NULL)
{
printf("Failed to run command\n");
return -1;
}
// Read the output a line at a time - output it.
while(!feof(fp))
{
if(fgets(str, 256, fp) != NULL)
{
result = -1;
strcat(out, str);
}
}
pclose(fp);
if (result != 0)
{
printf("%s\n", out);
return -1;
}
return 0;
}
But it doesn't work with insmod.
Is there any way to intercept all outputs when invoke insmod?

Resources