file exists by file name pattern
You can do a directory list with a pattern to check for files
string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
//file exist
}
check if file exists with a partial name in C
This is impossible in portable C because the C Standard Library does not have an API for enumerating files in a directory (then matching them yourself) let alone an API for matching file names by a pattern. This is because C predates modern notions of hierarchical directories (even the original Macintosh in 1984 didn't support subdirectories) - and because C still supports those systems today (think: microcontrollers).
In practice, you'd use your platform's filesystem API: on Unix-like/POSX systems including Linux that's done with dirent.h
- and for your problem specifically you'd use the glob
function: http://pubs.opengroup.org/onlinepubs/009604499/basedefs/glob.h.html
glob_t result;
const int ok = glob( "/tmp/God_of_War*", /*flags:*/ 0, /*errfunc:*/ NULL, &result );
if( 0 == ok ) {
for( size_t i = 0; i < result.gl_pathc; i++ ) {
puts( result.gl_pathv[i] );
}
}
else {
// error
}
globfree( &result);
On Windows, that's FindFirstFile
and FindNextFile
which you can use wildcards with, just like glob
.
WIN32_FIND_DATA result;
HANDLE searchHandle = FindFirstFile( "God_of_War*", &result);
if( searchHandle == INVALID_HANDLE_VALUE ) {
// handle error, use GetLastError() for details
}
else {
do {
puts( searchHandle.cFileName );
}
while( FindNextFile( searchHandle, &searchHandle ) );
DWORD lastError = GetLastError();
if( lastError != ERROR_NO_MORE_FILES ) {
// handle error
}
}
Check if filename matches particular pattern or not
Your can try with regular expressions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ConsoleAppRegex
{
class Program
{
static void Main(string[] args)
{
string[] fileNames = new string[] { "genprice20212604.xml",
"genprice20212704.xml",
"price20212604.xml",
"genprice20212704.txt"};
Regex re = new Regex(@"genprice[^\.]*.xml");
foreach (string fileName in fileNames)
{
if (re.Match(fileName).Success)
{
Console.WriteLine(fileName);
}
}
Console.ReadLine();
}
}
}
Check if a file matching a pattern exists
First make sure you have a File
object pointing to the directory where this file might need to be created. After that, you can call listFiles(FilenameFilter filter) on it. If it returns an array that is not of length 0, it means at least one file with a partial match for the name exists. You could additionally use this to detect incorrect situations (e.g. an array of length greater than 1 means there's too many files with that portion of the name).
To use this, you'd have to create an implementation of FilenameFilter. Make sure it has a constructor in which you pass the partial name or pattern for which you need to check. Regular expressions might not be necessary, a simple check to see if the current date in the desired format is contained in the file name would suffice.
Alternatively, you could use listFiles(FileFilter filter)
with an implementation of FileFilter instead of FilenameFilter
if there might be directories with dates in their names. Getting a single File
instance for checking instead of a File
for the directory plus a file name can make this easier, using method isDirectory()
of File
.
In C, checking for existence of file with name matching a pattern
You can use glob(3) (standardized by POSIX). You give it a wildcard pattern and it will search the filesystem for matches.
Example:
#include <glob.h>
#include <stdio.h>
int main(int argc, char **argv)
{
glob_t globbuf;
if (0==glob(argv[1], 0, NULL, &globbuf)){
char **a=globbuf.gl_pathv;
puts("MATCHES");
for(;*a;a++)
puts(*a);
}
globfree(&globbuf);
}
Running:
./a.out 'lockfile*'
should give you your lockfiles.
Check if file exists based on partial file name in Java
This code should help you.
First list out all the files in the folder
Start a loop and then get the fileName for each file and start
comparing the name to do your job.
String folderName = "."; // Give your folderName
File[] listFiles = new File(folderName).listFiles();
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i].isFile()) {
String fileName = listFiles[i].getName();
if (fileName.startsWith("MyTextFile_")
&& fileName.endsWith(".txt")) {
System.out.println("found file" + " " + fileName);
}
}
}
How can I check if a file exists with a certain string in its filename?
Sounds like you need the glob()
function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
<?php
foreach (glob('1_*.*') as $filename) {
echo "$filename\n";
}
?>
The above example will output something similar to:
1_foo.png
1_bar.png
1_something.png
Related Topics
How to Get All the Possible 3 Letter Permutations
Getting Selected Value of a Combobox
How to Access Resourcedictionary in Wpf from C# Code
More Elegant Exception Handling Than Multiple Catch Blocks
How to Generate Web Service Out of Wsdl
Razor Syntax Error Serializing ASP.NET Model to JSON with HTML.Raw
Change Forecolor Af a Special Word in Gridview Cell
C#/.Net Analysis Tool to Find Race Conditions/Deadlocks
C# Serialized JSON Date to Ruby
Using Xmlarrayitem Attribute Without Xmlarray on Serializable C# Class
Are Java and C# Regular Expressions Compatible
C# Generics Compared to C++ Templates
Dependency Injection with a Static Logger, Static Helper Class
Configure Multiple Database Entity Framework 6
Ef5 Code First - Changing a Column Type with Migrations
How to Get Img/Src or A/Hrefs Using HTML Agility Pack